【问题标题】:Calling C methods with Char** arguments from Python with ctypes使用 ctypes 从 Python 调用带有 Char** 参数的 C 方法
【发布时间】:2013-10-08 19:16:18
【问题描述】:

我需要一种方法,使用 ctypes 库将数组从 Python 传递给 char* 到 C 库。

我尝试过的一些方法会导致我出现分段错误,而另一些则导致信息垃圾。

【问题讨论】:

    标签: python c pointers char ctypes


    【解决方案1】:

    由于我一直在为这个问题苦苦挣扎,所以我决定写一个小的 HowTo 以便其他人可以受益。

    拥有这段 C 代码:

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

    我们想使用 ctypes 从 python 中调用它(关于 ctypes 的更多信息可以在之前的帖子中找到),所以我们写下以下代码:

    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)
    

    现在我读到它似乎很简单,但我很喜欢找到合适的类型传递给 ctypes 以避免分段错误...

    【讨论】:

    • 如果 C 函数修改了字符串,则使用 create_string_buffer 创建 c_char 数组,例如select = (POINTER(c_char) * len(string_set))(*map(create_string_buffer, string_set)).
    • 那我应该使用哪种 arg 类型?
    • 如果类型安全不是问题,您可以使用c_void_p。这将接受任何指针类型。您也可以使用POINTER(POINTER(c_char))。但是,ctypes 类型系统是无情的,所以如果你在混合 c_char_p 数组,你必须先 cast 以防止它发牢骚。
    • 非常感谢!不认为 void 可能是解决方案:-)
    • c_void_pfrom_param method 也接受 Python 整数和字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    相关资源
    最近更新 更多