简体   繁体   中英

Calling C methods with Char** arguments from Python with ctypes

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.

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...

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