简体   繁体   English

Python ctypes:使用'const char **'参数传递给函数

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

I want to pass a python list of strings to a C function expecting const char **. 我想将一个字符串的python列表传递给期望const char **的C函数。 I saw the question and solution here but it does not seem to work for me. 我在这里看到了问题和解决方案但它似乎对我不起作用。 The following sample code: 以下示例代码:

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

gives the following error: 给出以下错误:

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

What am I doing wrong? 我究竟做错了什么?


Addendum: 附录:

There seems to be a consensus, that this code should work. 似乎已达成共识,即此代码应该有效。 Here is how to reproduce the problem. 以下是如何重现问题。

The following four lines typed in my Python command-line illustrate my problem. 我的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
>>>

Another syntax to consider: 要考虑的另一种语法:

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

Works on my 2.7.1 and 3.1.3 installation. 适用于我的2.7.1和3.1.3安装。 Works on 3.2 if the array is a bytes instance, not str instance: 如果数组是一个字节实例,而不是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'

Looks like pre-3.2 allows coercion from str (Unicode) to bytes. 看起来像3.2之前允许从str(Unicode)到字节的强制。 This is probably not a bug, since 3.X series has tried to eliminate automatic conversion of bytes<->str (explicit is better than implicit). 这可能不是一个bug,因为3.X系列试图消除字节< - > str的自动转换(显式优于隐式)。

The sample python code is correct. 示例python代码是正确的。

Can you paste the whole code? 你能粘贴整个代码吗?

In this case, I am guessing the your string contains embedded NUL bytes, and throws this TypeError exception. 在这种情况下,我猜你的字符串包含嵌入的NUL字节,并抛出此TypeError异常。

Hope this link helps: http://docs.python.org/c-api/arg.html 希望此链接有所帮助: http//docs.python.org/c-api/arg.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM