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

故事扮演 提交于 2021-02-19 05:01:47

问题


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:


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



来源:https://stackoverflow.com/questions/19136347/calling-c-methods-with-char-arguments-from-python-with-ctypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!