我正在尝试使用 ctypes 将 2 个字符串从 Python (3.2) 发送到 C。这是我在 Raspberry Pi 上的项目的一小部分。为了测试 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 实例”。
希望有人能告诉我哪里错了。 提前致谢。
最佳答案
感谢 Eryksun 的解决方案:
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.argtypes = [ctypes.c_char_p, ctypes.char_p]
my_c_function(b_string1, b_string2)
关于使用ctypes将python字符串对象转换为c char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27127413/