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

标签 c string python-3.x ctypes

我正在尝试使用 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/

相关文章:

c++ - 链接列表 (C/C++)。同时创建列表结构和节点结构有哪些优点/缺点?

c - 为什么我不能在 Ubuntu 中打开我的 txt 文件?

python-3.x - 谷歌云 python 项目有本地主机错误

python - 如何从 TableModel 将标题添加到 qml TableView

C-二叉搜索树

c - 间接错误的级别

Python:如何将特定特征的文本添加到文本文件

python - 反转 Python 字符串的切片

c# - 在 .Net 中为整个句子实现 soundex

python - 如何从 StackDriver Logging API 反序列化 App Engine 应用程序日志?