简体   繁体   中英

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 **. 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 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. Works on 3.2 if the array is a bytes instance, not str instance:

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. This is probably not a bug, since 3.X series has tried to eliminate automatic conversion of bytes<->str (explicit is better than implicit).

The sample python code is correct.

Can you paste the whole code?

In this case, I am guessing the your string contains embedded NUL bytes, and throws this TypeError exception.

Hope this link helps: http://docs.python.org/c-api/arg.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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