[英]How to open a pickled file in both read and write simultaneously in python?
[英]Python and C file read/write simultaneously
我有一些C代码,已在Python中进行了扩展。 扩展的C代码具有将某些结构附加到二进制文件的功能:
void writefunction(const struct struct1* some,const u_char* struct2){
f=fopen('save.bin',"ab");
if(f==NULL){
printf("Unable to open file");
exit(-1);
}
fwrite(some,sizeof(struct struct1),1,f);
fwrite(struct2,sizeof(u_char),4,f);
fclose(f);
}
现在,我已经在Python中导入了代码。 我想在Python中启动两个线程:一个将运行此writefunction(),另一个将读取相同的文件。 writefunction在一个线程中正常工作,但是从文件读取的Python函数不起作用。
我究竟做错了什么?
不要这样
这里的问题是,“ save.bin”文件的内容取决于您使用的C编译器-也许还取决于传递给编译器的某些命令行参数。
结构struct1
如何内部保存在内存中取决于编译器-至少在使用位域时; 编译器可能还会添加填充(请参见下面的示例)。 您将内部存储器结构写入文件。
如果要与用不同语言编写的程序(并可能在不同服务器上运行)交换数据,则应使用一些“有线”(序列化)协议对其进行转换。
建议:也许要使用JSON或XML。
填充结构的示例:
#include <stdio.h>
struct struct1 {
char a;
long b;
};
int main() {
printf("%d %d %d\n", sizeof(char), sizeof(long), sizeof(struct struct1));
return 0;
}
一种可能的输出是:
1 8 16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.