我正在尝试使用 Python 将用 C 编写的二进制文件与 HDF5 文件进行转换。要读取二进制文件,Python 的工作方式如下:
pos=np.fromfile(f, count=npt*3, dtype='f4').reshape((npt, 3))
要编写我尝试过的相同的东西,但没有成功,array.tofile() 现在我正在尝试使用这样的 ctypes(将网上找到的不同答案拼接在一起):
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)