蟒蛇转换字符串对象到C的char *使用ctypes的 [英] Converting python string object to c char* using ctypes
问题描述
我想在Python(3.2)发送2字符串使用C ctypes的。这是我对我的树莓派项目的一小部分。以测试是否C函数正确地接收到的字符串,我把它们中的一个在一个文本文件。
I am trying to send 2 strings from Python (3.2) to C using ctypes. This is a small part of my project on my Raspberry Pi. To test if the C function received the strings correctly, I place one of them in a text file.
的Python code
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 $ 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..
}
问题
只有串的首字母出现在文本文件中。
Only the first letter of the string appears in the text file.
我试过很多方法了Python string对象转换与ctypes的。
I've tried many ways to convert the Python string object with ctypes.
- ctypes.c_char_p
- ctypes.c_wchar_p
- ctypes.create_string_buffer
使用这些转换我不断收到错误错误类型或字节或预期,而不是STR例如整数地址。
With these conversions I keep getting the error "wrong type" or "bytes or integer address expected instead of str instance".
我希望有人能告诉我在哪里出了问题。
先谢谢了。
I hope someone can tell me where it goes wrong. Thanks in advance.
推荐答案
由于Eryksun解决方案:
Thanks to Eryksun the solution:
的Python code
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 *使用ctypes的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!