想知道如何在Cython中读取二进制文件并将字符串返回给Python。我有以下但是在fread(缓冲区..)行上收到错误。我不熟悉C / 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?
答案 0 :(得分:2)
您错误地使用了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)