2017-06-23 74 views
1

想知道如何在Cython中讀取二進制文件並將字符串返回給Python。我有以下,但在fread(buffer ..)行上出現錯誤。我不是超級熟悉C /用Cython所以如果有在功能更易於建造讀二進制文件成將不勝感激Cython將二進制文件讀入字符串並返回

def read_file2(filename): 
cdef FILE * cfile 
cdef long length 
filename_byte_string = filename.encode("UTF-8") 
cdef char* fname = filename_byte_string 
cdef char * buffer; 

cfile = fopen(fname, "rb") 
if cfile: 
    fseek (cfile, 0, SEEK_END) 
    length = ftell(cfile) 
    fseek (cfile, 0, SEEK_SET) 
    buffer = <char*>malloc(length) 
    if buffer: 
     fread(&buffer, 1, length, fname) 

解決的字符串:我收到以下錯誤:

read_numpy.pyx:64:33: Cannot assign type 'char *' to 'FILE *' 

如何將緩衝區對象或包含文件字節表示的字符串返回給Python?

回答

1

您錯誤地使用fname而不是cfile

cfile = fopen(fname, "rb") 
if cfile: 
    fseek (cfile, 0, SEEK_END) 
    length = ftell(cfile) 
    fseek (cfile, 0, SEEK_SET) 
    buffer = <char*>malloc(length) 
    if buffer: 
     fread(&buffer, 1, length, fname) <--- 

這最後一行應該是:

fread(&buffer, 1, length, cfile) 
相關問題