2011-02-24 80 views
1

我想将一个python的字符串列表传递给C函数,期望const char **。我看到了问题和解决方案here,但它似乎不适合我。下面的示例代码:Python的ctypes:传递给'const char **'参数的函数

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 
>>> 
+2

哪里出错?该代码似乎工作。 – 2011-02-24 12:43:21

+0

在我的机器上它没有。你在用什么系统?我在WinXP上使用Python 3.2。 - 这能改变吗? – ARF 2011-02-24 13:00:13

+0

尝试'argList = [b'abc',b'def']'。 – 2011-02-26 04:17:34

回答

1

示例python代码是正确的。

你能粘贴整个代码吗?

在这种情况下,我猜你的字符串包含嵌入的NUL字节,并引发此TypeError异常。

希望这有助于链接:http://docs.python.org/c-api/arg.html

+0

请参阅我的问题中关于如何重现问题的补充。 – ARF 2011-02-24 13:30:34

+0

也许这是python verion的一个准备好的bug。 – Xirui 2011-02-24 13:38:06

+0

我在linux2上使用Python 3.1.2(release31-maint,2010年9月17日,20:34:23) [GCC 4.4.5]。我输入相同的代码,它不会给出任何错误消息。使用一些较旧的版本尝试代码。 – Xirui 2011-02-24 13:40:07

3

另一种语法来考虑:

>>> 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安装。工作在3.2,如果所述阵列是个字节实例,而不是STR实例:

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)的强迫字节。这可能不是一个bug,因为3.X系列试图消除自动转换字节< - > str(显式比隐式更好)。

相关问题