我想使用ctypes从Python(3.2)发送2个字符串到C。这是我在我的树莓派上进行的项目的一小部分。为测试C函数是否正确接收了字符串,我将其中一个放置在文本文件中。
Python代码:
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.create_string_buffer(b_string1),
ctypes.create_string_buffer(b_string2))
C 代码
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..
}
问题
文本文件中只有字符串的第一个字母。
我尝试了很多种方法来使用ctypes转换Python字符串对象。
- ctypes.c_char_p
- ctypes.c_wchar_p
- ctypes.create_string_buffer
但是这些转换都会报错,提示"wrong type"或者"bytes or integer address expected instead of str instance"。
希望有人能告诉我出了什么问题。提前致谢。
my_c_function.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
。由于参数是const
,因此可以简单地调用my_c_function(b_string1, b_string2)
。 - Eryk Sun"\\"
,但正斜杠则不需要。只需写成"/home/pi/Desktop/out.txt"
即可。 - Eryk Sunbuf = ctypes.create_string_buffer(bstr)
,其等价于buf = (ctypes.c_char * (len(bstr) + 1))();
buf.value = bstr
。 - Eryk Sun