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

Lit*_*One 17 c string ctypes python-3.x

我试图使用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))
Run Code Online (Sandbox Code Playgroud)

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..
}
Run Code Online (Sandbox Code Playgroud)

问题

只有字符串的第一个字母出现在文本文件中.

我已经尝试了很多方法来使用ctypes转换Python字符串对象.

  • ctypes.c_char_p
  • ctypes.c_wchar_p
  • ctypes.create_string_buffer

通过这些转换,我不断收到错误"错误类型"或"预期的字节或整数地址而不是str实例".

我希望有人可以告诉我哪里出了问题.提前致谢.

Lit*_*One 22

感谢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)
Run Code Online (Sandbox Code Playgroud)

  • 你知道吗,强迫症! (3认同)
  • `my_c_function.argtypes = [ctypes.c_char_p, ctypes_char_p]` 您的意思是 `my_c_function.argtypes = [ctypes.c_char_p, ctypes.char_p]` (注意 `.` 而不是 `_`)? (2认同)
  • 哈哈,五年后有人注意到或觉得费心指出这一点。谢谢你,我在答案中编辑了它。 (2认同)

Aks*_*sel 12

我想你只需要使用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))
Run Code Online (Sandbox Code Playgroud)

如果需要可变字符串,则使用create_string_buffer()并使用ctypes.cast()将它们转换为c_char_p.