Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert item into c_char_p array

Tags:

python

ctypes

I want to pass an array of char pointer to a C function.

I refer to http://docs.python.org/library/ctypes.html#arrays

I write the following code.

from ctypes import *

names = c_char_p * 4
# A 3 times for loop will be written here.
# The last array will assign to a null pointer.
# So that C function knows where is the end of the array.
names[0] = c_char_p('hello')

and I get the following error.

TypeError: '_ctypes.PyCArrayType' object does not support item assignment

Any idea how I can resolve this? I want to interface with

c_function(const char** array_of_string);
like image 891
Cheok Yan Cheng Avatar asked Jan 14 '11 01:01

Cheok Yan Cheng


1 Answers

What you did was to create an array type, not an actual array, so basically:

import ctypes
array_type = ctypes.c_char_p * 4
names = array_type()

You can then do something along the lines of:

names[0] = "foo"
names[1] = "bar"

...and proceed to call your C function with the names array as parameter.

like image 109
Jim Brissom Avatar answered Oct 16 '22 22:10

Jim Brissom