简体   繁体   English

在python中编写二进制文件以供C读取

[英]Writing binary files in python to be read by C

I have to use a program written in C that read data from a binary file in this way 我必须使用用C编写的程序,以这种方式从二进制文件中读取数据

nCnt = 0;
for (i=0;i<h.nsph;++i) {
    fread(&gp,sizeof(struct gas_particle),1,fp);
    if (bGas) {
        kd->p[nCnt].iOrder = nCnt;
        for (j=0;j<3;++j) kd->p[nCnt].r[j] = gp.pos[j];
        ++nCnt;
        }

    }

The above code is not the whole code of the program I'm using but only the part relevant for my question. 上面的代码不是我正在使用的程序的整个代码,而只是与我的问题相关的部分。 I need to read the positions of nCnt particles, ie the coordinate for each particle. 我需要读取nCnt粒子的位置,即每个粒子的坐标。 I have these positions in a python array, which looks like this 我在python数组中有这些位置,看起来像这样

 pos=array([[[ 0.4786236 ,  0.49046784,  0.48877147],
    [ 0.47862025,  0.49042325,  0.48877267],
    [ 0.47862737,  0.49039413,  0.4887735 ],
    ..., 
    [ 0.4785084 ,  0.49032556,  0.48860968],
    [ 0.47849332,  0.49041115,  0.48877266],
    [ 0.47849161,  0.49041022,  0.48877176]]])

How should I write this array in a binary file so that the C code would read it fine? 我应该如何在二进制文件中编写此数组,以便C代码可以正常读取?

Use the python module array and it's tofile() method to write the data in a format which C can read or the IO routines if you use numpy . 使用python模块array ,它的tofile()方法以C可以读取的格式写入数据, 如果使用numpy 则以 IO例程写入数据。

With the number of digits, the 'f' format (float) should work. 使用数字位数, 'f'格式(浮点数)应该有效。

In C, you can read each line like so: 在C中,您可以像这样读取每一行:

float values[3];
fread( values, sizeof( float ), 3, fh );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM