3

I need a way to pass an array to char* from Python using ctypes library to a C library.

Some ways I've tried lead me to segmentation faults, others to rubbish info.

1 Answer 1

3

As I've been struggling with this issue for some time, I've decided to write a small HowTo so other people can benefit.

Having this C piece of code:

void passPointerArray(int size, char **stringArray) {
  for (int counter=0; counter < size; counter++) {
    printf("String number %d is : %s\n", counter, stringArray[counter]);
  }
}

We want to call it from python using ctypes (more info about ctypes can be found in a previous post), so we write down the following code:

def pass_pointer_array():
  string_set = [
    "Hello",
    "Bye Bye",
    "How do you do"
  ]

  string_length = len(string_set)

  select_type = (c_char_p * string_length)
  select = select_type()

  for key, item in enumerate(string_set):
    select[key] = item

  library.passPointerArray.argtypes = [c_int, select_type]
  library.passPointerArray(string_length, select)

Now that I read it it appears to be very simple, but I enjoyed a lot finding the proper type to pass to ctypes in order to avoid segmentation faults...

Sign up to request clarification or add additional context in comments.

5 Comments

If the C function modifies the strings, create c_char arrays with create_string_buffer, e.g. select = (POINTER(c_char) * len(string_set))(*map(create_string_buffer, string_set)).
And which arg type should I use then?
If type safety isn't a concern you can just use c_void_p. That will accept any pointer type. You can also use POINTER(POINTER(c_char)). However, the ctypes type system is unforgiving, so if you're mixing in c_char_p arrays you'll have to cast first to keep it from whining.
Thanks a lot! didn't think void could be the solution :-)
The from_param method of c_void_p also accepts Python integers and strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.