Python-C API : Trouble packing C strings into a tuple

标签 python c python-c-api

在下面的代码中,我试图将两个以 null 结尾的 C 字符串(字符指针)打包到一个 Python 元组中。

printf("word1 = '%s', word2 = '%s'\n", words1->wordArray[i], words2->wordArray[i]);
cmpArgs = Py_BuildValue("ss", words1->wordArray[i], words2->wordArray[i]);
printf("%s\n", PyString_AsString(PyTuple_GetItem(cmpArgs, 0)));

这会产生如下输出:

word1 = '20', word2 = '20'
i┴

为什么元组中的字符串与元组外的字符串不同?我究竟做错了什么?另外,我是否需要担心增加和减少这个元组的引用计数? (我正在创建它以传递给作为 PyObject* 传递给 C 的 Python 函数)

最佳答案

我想我明白了——我之前使用堆栈空间以一种奇怪的方式存储单词。我开始为他们手动分配堆上的空间,这似乎已经修复了它。

关于Python-C API : Trouble packing C strings into a tuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13182549/

相关文章:

Python:惰性子模块导入使父模块无效 > UnboundLocalError - 但为什么呢?

C - fork() & execl() & 循环 + "half pyramid output"

c - 访问邻接表时使用什么符号?

python - 从 C++ 停止嵌入式 Python 提示

python - 使用 C python api 时消息长度不正确

python - 在 Python 中生成多元分布(数据点)

python - 如何在 Windows 上使用 Python 3.5 创建可执行文件?

python - 导入错误: cannot import name 'main'

c - MSP430 的 CCS 中出现错误 : Expected an identifier,

python - 使用 Python/C API 传递 C 指针