使用ctypes将python字符串对象转换为c char *

我试图使用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字符串对象。

  • 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) 

我想你只需要使用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。

你考虑过使用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) 

注意我.encode('utf-8')如果源文件已经是UTF-8,则必须使用.encode('utf-8')