将C++内存文件加载到Python中

3

我有一个文件,在C++中我使用以下代码将其加载到数组中:


int SomeTable[10000];

int LoadTable()
{
    memset(SomeTable, 0, sizeof(SomeTable));
    FILE * fin = fopen("SomeFile.dar", "rb");
    size_t bytesread = fread(SomeTable, sizeof(SomeTable), 1, fin);
    fclose(fin);
}

这个文件是由 10000 个整数的二进制代码组成的,因此在 C++ 中可以直接加载到内存中。在 Python 中有没有更好的方法?

祝一切顺利, Rok


2
如何从文件中读取。http://docs.python.org/tutorial/inputoutput.html - DumbCoder
https://dev59.com/WnNA5IYBdhLWcg3wrPyq - DumbCoder
1个回答

2

让我们使用简短的C代码将数组写入文件:

int main ()
{
  FILE * pFile;
  int a[3] = {1,2,3};
  pFile = fopen ( "file.bin" , "wb" );
  fwrite (a , 1 , sizeof(a) , pFile );
  fclose (pFile);
  return 0;
}

二进制文件可以直接加载到Python数组中。请参考Python数组文档
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import array
>>> a=array.array('l') # 'l' is the type code for signed integer
>>> file=open('file.bin','rb')
>>> a.read(file,3)
>>> print a
array('l', [1, 2, 3])
>>> print a[0]
1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接