我试图使用ctypes从Python(3.2)向C发送两个字符串.这是我关于覆盆子圆周率的项目的一小部分.为了测试C函数是否正确接收到字符串,我将其中一个字符串放入文本文件中.

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.创建字符串缓冲区(b_string1),
              ctypes.创建字符串缓冲区(b_string2))

C code

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..
}

The problem

文本文件中只显示字符串的第一个字母.

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

  • ctypes.c_char_p
  • ctypes.c_wchar_p
  • ctypes.创建字符串缓冲区

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

我希望有人能告诉我哪里出了问题.

推荐答案

多亏了Eryksun,解决方案:

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)

Python-3.x相关问答推荐

我有个问题继承遗产合伙人

按长度和字母数字对Pandas 数据帧列进行排序

为什么我无法在django中按月筛选事件?

aiogram机器人中处理文本输入异常而不是按钮点击的回调函数.

需要找到完全匹配并使用正则表达式替换

如果集合大于 len(x),则 pandas 在重复的行中拆分集合列

pytorch 中 mps 设备的 manual_seed

如何在不使用循环的情况下根据另一个数组的索引值将 numpy 数组中不同通道的值设置为零?

根据另一个数据帧中的位置从主数据帧中提取子序列

python2和python3中的列表生成器

Visual Studio Code 中的 Python 3.x 类型提示

基本 Flask 应用程序未运行(TypeError:模块中缺少必填字段type_ignores)

django.core.exceptions.ImproperlyConfigured

str.format_map(mapping) 和 str.format 有什么区别

sys.stdin.readline() 和 input():读取输入行时哪个更快,为什么?

如何用pymongo连接远程mongodb

如何将二进制(字符串)转换为浮点值?

计算两个文件的行差异的最有效方法是什么?

Python - 类 __hash__ 方法和集合

在 Ipython 中使用 Pylint (Jupyter-Notebook)