Python ctypes : passing to function with 'const char ** ' argument

标签 python c ctypes

我想将 python 字符串列表传递给需要 const char ** 的 C 函数。看到题解了here但它似乎对我不起作用。以下示例代码:

argList = ['abc','def']
options = (ctypes.c_char_p * len(argList))()
options[:] = argList

出现以下错误:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: string or integer address expected instead of str instance

我做错了什么?


附录:

似乎已达成共识,即此代码应该有效。以下是重现问题的方法。

在我的 Python 命令行中输入的以下四行说明了我的问题。

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> argList = ['abc', 'def']
>>> options = (c_char_p * len(argList))()
>>> options[:] = argList
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string or integer address expected instead of str instance
>>>

最佳答案

要考虑的另一种语法:

>>> from ctypes import *
>>> a = 'abc def ghi'.split()
>>> b=(c_char_p * len(a))(*a)
>>> b[0]
'abc'
>>> b[1]
'def'
>>> b[2]
'ghi'

适用于我的 2.7.1 和 3.1.3 安装。如果数组是 bytes 实例而不是 str 实例,则适用于 3.2:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> a = b'abc def ghi'.split()
>>> b=(c_char_p * len(a))(*a)
>>> b[0]
b'abc'
>>> b[1]
b'def'
>>> b[2]
b'ghi'

3.2 之前的版本似乎允许从 str (Unicode) 强制转换为 bytes。这可能不是一个错误,因为 3.X 系列已经尝试消除 bytes<->str 的自动转换(显式优于隐式)。

关于Python ctypes : passing to function with 'const char ** ' argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5104015/

相关文章:

python - 使用 Python 遍历给定搜索短语和 URL 的 Google 搜索结果

c - 在具有重复值的未排序数组中查找缺失的数字

C程序重定向到一个文件

c - 字符串文字导致小内存泄漏?

python - IO完成端口 key 混淆

python - 将指向数组值的指针从 Cython 传递到 C

python - pandas - append 具有不同列数的新行

python - 洗牌一小组项目

python - 乘以相邻元素

python - 如何打包分发使用共享库的 python 模块?