我正在尝试使用Python将用C编写的二进制文件与HDF5文件进行转换。
要读取二进制文件,Python的工作方式如下:
pos=np.fromfile(f, count=npt*3, dtype='f4').reshape((npt, 3))
为了写出我尝试过的同样的东西,但没有成功,array.tofile(),现在我正尝试使用类似的ctypes(将web上找到的不同答案拼接在一起):
import ctypes as c
print "Loading C libraries with ctype"
libc = c.CDLL("libc.so.6") # Linux
# fopen()
libc.fopen.restype = c.c_void_p
def errcheck(res, func, args):
if not res: raise IOError
return res
libc.fopen.errcheck = errcheck
# errcheck() could be similarly defined for `fwrite`, `fclose`
c_int_p = c.POINTER(c.c_int)
c_float_p = c.POINTER(c.c_float)
c_double_p = c.POINTER(c.c_double)
def c_write(data, f, numpy_type, c_type_p, nbyte, count):
data = data.astype(numpy_type)
data_p = data.ctypes.data_as(c_type_p)
nitems = libc.fwrite(data_p, nbyte, count, f)
if nitems != data.size: # not all data were written
print "Not all data were written, exit..."
sys.exit()
c_write(pos, f, np.int32, c_int_p, 4, npart.size)
最佳答案
您可能应该研究一下struct
模块,它非常适合以最低的字节/字节级别打包和解包数据。
关于python - python和C之间的二进制I/O,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12782671/