我想使用ctypes创建一个python数据类型,它与c数据类型&;const char**&;相匹配,它类似于指针数组。但是,我无法在Python中编写此代码。简化的c函数头看起来像这样:
int foo(int numOfProp, const char** propName, const char** propValue);
在C中,正确的函数调用应该是这样的:
const char *PropName[2];
PropName[0] = "Prop_Index_1";
PropName[1] = "Prop_Index_2";
const char *PropValue[2];
PropValue[0] = "10";
PropValue[1] = "20";
stream_id = (*foo)(2, PropName, PropValue);
基本上,该函数接受两个数组(一对name和value)以及两个数组的长度,并返回一个流ID。当加载DLL时,我可以看到函数期望属性数组使用ctypes数据类型:
"LP_c_char_p">
然而,我真的很难基于字符串列表创建这种数据类型。
我的第一次尝试(基于我如何创建一个指向指针数组的Python ctypes指针)看起来像这样:
# set some dummy values
dummy_prop_values = [
"10",
"20"
]
# create property dict
properties = {
f"Prop_Index_{i}": dummy_prop_values[i] for i in range(len(dummy_prop_values))
}
def first_try():
# create a dummy ctype string
ctypes_array = ctypes.c_char_p * 2
# create empty c-type arrays for the stream properties
prop_names = ctypes_array()
prop_values = ctypes_array()
# fill the empty arrays with their corresponding values
for i, (prop_name, prop_value) in enumerate(properties.items()):
prop_names[i] = prop_name.encode()
prop_values[i] = prop_value.encode()
# get pointer to properties
ptr_prop_names = ctypes.pointer(prop_names)
ptr_prop_values = ctypes.pointer(prop_values)
return ptr_prop_names, ptr_prop_values
当我把返回值交给函数foo(这实际上是有意义的,因为我显式地创建了一个长度为2的数组)时,它会抛出这种错误…我不知道这对另一个问问题的人是如何/为什么起作用的):
ctypes.ArgumentError: argument 2: <class 'TypeError'>: expected LP_c_char_p instance instead of LP_c_char_p_Array_2
我的第二次尝试(或多或少基于我自己的想法)是这样的:
def second_try():
# convert properties to lists
prop_names = [x for x in properties.keys()]
prop_values = [x for x in properties.values()]
# concat list elements, zero terminated
# but I guess this is wrong anyway because it leads to an early string-termination (on byte-level)...?
prop_names = ctypes.c_char_p("