我正在尝试使用ctypes从Python(3.2)向C发送2个字符串。这是我的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字符串对象。
通过这些转换,我不断收到错误“错误类型”或“预期的字节或整数地址而不是str实例”。
我希望有人可以告诉我哪里出错了。 提前谢谢。
答案 0 :(得分:18)
感谢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)
答案 1 :(得分:9)
我认为您只需要使用c_char_p()而不是create_string_buffer()。
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.c_char_p(b_string1),
ctypes.c_char_p(b_string2))
如果你需要可变字符串,那么使用create_string_buffer()并使用ctypes.cast()将它们转换为c_char_p。
答案 2 :(得分:1)
您是否考虑过使用SWIG?我自己没有尝试过,但是在不改变你的C源的情况下它会是什么样子:
/*mymodule.i*/
%module mymodule
extern void my_c_function(const char* str1, const char* str2);
这会使你的Python源像(跳过编译)一样简单:
import mymodule
string1 = "my string 1"
string2 = "my string 2"
my_c_function(string1, string2)
请注意,如果您的源文件已经是UTF-8,我不确定.encode('utf-8')
。