从蟒蛇传递字符串列表/ ctypes的为C函数期望的char ** [英] Passing a list of strings to from python/ctypes to C function expecting char **

查看:157
本文介绍了从蟒蛇传递字符串列表/ ctypes的为C函数期望的char **的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C函数,它期望一个列表\\ 0结尾的字符串作为输入:

 无效external_C(INT长度为const char ** string_list){
   //检查string_list的内容 - 但不能修改它。
}

在Python(与ctypes的)我想基于Python的字符串列表上调用这个函数:

 高清call_c(string_list):
    lib.external_C(??)call_c([字符串1,字符串2,最后的字符串])

这是如何建立在Python端数据结构的任何提示吗?注意,我保证C函数不会改变在string_list字符串的内容。

问候

乔金 -


解决方案

 高清call_c(L):
    ARR =(ctypes.c_char_p * LEN(L))()
    ARR [:] = L
    lib.external_C(LEN(L),ARR)

I have a C function which expects a list \0 terminated strings as input:

void external_C( int length , const char ** string_list) { 
   // Inspect the content of string_list - but not modify it.
} 

From python (with ctypes) I would like to call this function based on a list of python strings:

def call_c( string_list ):
    lib.external_C( ?? )

call_c( ["String1" , "String2" , "The last string"])

Any tips on how to build up the datastructure on the python side? Observe that I guarantee that the C function will NOT alter content of the strings in string_list.

Regards

joakim

解决方案

def call_c(L):
    arr = (ctypes.c_char_p * len(L))()
    arr[:] = L
    lib.external_C(len(L), arr)

这篇关于从蟒蛇传递字符串列表/ ctypes的为C函数期望的char **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆