将字符串列表从python/ctypes传递给C函数,期望char**

Joa*_*ove 20 c python ctypes

我有一个C函数,它期望list\0终止的字符串作为输入:

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

从python(使用ctypes)我想基于python字符串列表调用此函数:

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

call_c( ["String1" , "String2" , "The last string"])
Run Code Online (Sandbox Code Playgroud)

有关如何在python端构建数据结构的任何提示?注意我保证C函数不会改变string_list中字符串的内容.

问候

乔金 -

hab*_*bit 25

def call_c(L):
    arr = (ctypes.c_char_p * len(L))()
    arr[:] = L
    lib.external_C(len(L), arr)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在 Python 3.x 中,字符串默认为 unicode,因此您应该通过 `s.encode('utf-8')` 或 `bytes(s, 'utf-8')`(或您想使用的任何编码都不是 UTF-8)。 (2认同)

use*_*005 5

非常感谢你; 这很像魅力.我还做了一个像这样的替代变体:

def call_c( L ):
    arr = (ctypes.c_char_p * (len(L) + 1))()
    arr[:-1] = L
    arr[ len(L) ] = None
    lib.external_C( arr )
Run Code Online (Sandbox Code Playgroud)

然后在C函数中,我遍历(char**)列表,直到找到NULL.


小智 5

使用 ctypes

创建到期列表(字符串)

expiries = ["1M", "2M", "3M", "6M","9M", "1Y", "2Y", "3Y","4Y", "5Y", "6Y", "7Y","8Y", "9Y", "10Y", "11Y","12Y", "15Y", "20Y", "25Y", "30Y"]
Run Code Online (Sandbox Code Playgroud)

发送字符串数组的逻辑

通过在数组中循环将字符串数组转换为字节数组

 expiries_bytes = []
    for i in range(len(expiries)):
        expiries_bytes.append(bytes(expiries[i], 'utf-8'))
Run Code Online (Sandbox Code Playgroud)

逻辑ctypes启动一个长度为数组的指针

expiries_array = (ctypes.c_char_p * (len(expiries_bytes)+1))()
Run Code Online (Sandbox Code Playgroud)

将字节数组分配给指针

expiries_array[:-1] = expiries_bytes
Run Code Online (Sandbox Code Playgroud)