【发布时间】:2015-01-23 11:56:54
【问题描述】:
我正在尝试使用 ctypes 将 2 个字符串从 Python (3.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
通过这些转换,我不断收到错误“错误类型”或“预期的字节或整数地址而不是 str 实例”。
我希望有人能告诉我哪里出错了。 提前致谢。
【问题讨论】:
-
设置
my_c_function.argtypes = [ctypes.c_char_p, ctypes.c_char_p]。然后,因为参数是const,所以直接调用为my_c_function(b_string1, b_string2)。 -
仅供参考,文字反斜杠字符需要转义为
"\\",但正斜杠不需要。只是"/home/pi/Desktop/out.txt"。 -
@eryksun 感谢您的回复。它现在可以工作了,我完全忘记了我还在 c_wchar_p 上设置了 argtypes。关于斜线,我总是把它们弄混。
-
只在函数修改字符串时使用
buf = ctypes.create_string_buffer(bstr)。相当于buf = (ctypes.c_char * (len(bstr) + 1))();buf.value = bstr。
标签: c string python-3.x ctypes