我试图使用ctypes从Python(3.2)向C发送两个字符串.这是我关于覆盆子圆周率的项目的一小部分.为了测试C函数是否正确接收到字符串,我将其中一个字符串放入文本文件中.
Python code
string1 = "my string 1"
string2 = "my string 2"
# create byte objects from the strings
b_string1 = string1.encode('utf-8')
b_string2 = string2.encode('utf-8')
# send strings to c function
my_c_function(ctypes.创建字符串缓冲区(b_string1),
ctypes.创建字符串缓冲区(b_string2))
C code
void my_c_function(const char* str1, const char* str2)
{
// Test if string is correct
FILE *fp = fopen("//home//pi//Desktop//out.txt", "w");
if (fp != NULL)
{
fputs(str1, fp);
fclose(fp);
}
// Do something with strings..
}
The problem
文本文件中只显示字符串的第一个字母.
我已经try 了很多方法来用ctypes转换Python字符串对象.
- ctypes.c_char_p
- ctypes.c_wchar_p
- ctypes.创建字符串缓冲区
通过这些转换,我不断得到错误"错误的类型"或"需要字节或整数地址而不是str实例".
我希望有人能告诉我哪里出了问题.