8

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);
TryPyPy
  • 5,886
  • 4
  • 32
  • 63
Cheok Yan Cheng
  • 49,649
  • 117
  • 410
  • 768

1 Answers1

16

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.

Jim Brissom
  • 27,745
  • 2
  • 34
  • 33