带点指针的C函数

问题描述 投票:0回答:1

我有一个在C / C ++ DLL中定义的方法,需要2个参数

void SetLines(char** args,int argCount);

我需要从Python调用它,这样做的正确方法是什么。

from ctypes import *
path="test.dll"
lib = cdll.LoadLibrary(path)
Lines=["line 2","line 2"]
lib.SetLines(Lines,len(lines))
print(code)

执行Python代码会出现以下错误:

Traceback (most recent call last):
  File "<test.py>", line 6, in <module>
ctypes.ArgumentError: argument 1: <class 'TypeError'>: Don't know how to convert parameter 1
python c ctypes
1个回答
1
投票

经过一些代码挖掘,我弄清楚了:

任何接受指向值列表的指针的C / C ++参数都应该用python包装

MyType=ctypes.ARRAY(/*any ctype*/,len)
MyList=MyType()

并充满了

MyList[index]=/*that ctype*/

在我的案例中,解决方案是:

from ctypes import *
path="test.dll"
lib = cdll.LoadLibrary(path)

Lines=["line 1","line 2"]
string_pointer= ARRAY(c_char_p,len(Lines)) 
c_Lines=string_pointer()
for i in range(len(Lines)):
    c_Lines[i]=c_char_p(Lines[i].encode("utf-8"))

lib.SetLines(c_Lines,len(lines))
© www.soinside.com 2019 - 2024. All rights reserved.