【发布时间】:2020-09-09 09:54:54
【问题描述】:
这是加载 erf_utils_io_D.dll 的 module.py script,其中包含 io.c 和 io.h 文件
我成功加载了库并传递了 ctype 参数,例如
c_int, c_float, POINTER(c_int), POINTER(c_Float)
module.py
//python code module.py
import sys
from ctypes import *
#load the required library and make sure the folder where erf_utils_io_D.dll is present
dll = CDLL('D:\\erf_utils_python\\erf_utils_io.dll')
getContourResults = dll.getContourResults
class Utility(object):
def __init__(self):
print('i am inside init')
self.stagename = "post"
self.stateids = (c_int * 1) (2934)
self.stateidcount = 1
self.entityidcount = 1
self.entityid = (c_int * 1) (1)
self.entitytype = "FPM"
self.variablecount = 1
self.ores = [1.0]
self.filename ='allinone_RESULT.erfh5'
#This is how char** is treted in python for variablegroup
self.variablegroup = ["FPM_Mach_Number"]
self.string_length = len(self.variablegroup)
self.select_type = (c_wchar_p * self.string_length)
self.select = self.select_type()
for key, item in enumerate(self.variablegroup):
self.select[key] = item
#This is how char** is treated infor variable
self.variable = ["FPM_Mach_Number"]
self.var_len = len(self.variable)
self.var_type = (c_wchar_p * self.var_len)
self.variable_list = self.var_type()
for key, item in enumerate(self.variable):
self.variable_list[key] = item
def run(self):
getContourResults.argtypes = (POINTER(c_char_p), POINTER(c_char_p), c_int, POINTER(c_int),
c_int, POINTER(c_int), POINTER(c_char), c_int, self.select_type ,
self.var_type, POINTER(c_float))
getContourResults.restype = (c_int)
err = getContourResults(self.filename, self.stagename, self.stateidcount,
self.stateids, self.entityidcount,self.entityid, self.entitytype, self.variablecount, self.select, self.variable_list, self.ores)
reader = Utility()
reader.run()
code.cpp 看起来像这样
extern "C"
{
#endif
__declspec(dllexport) int getContourResults(char* iFilename, char* iStagename, int iStateidCnt, int* Stateids,
int iEntityIdCount, int* iEntityids, char* iEntityType,
int iVariablecnt, char** iVariablegroup, char** ivariable,
float* oResults);
}
请告诉我如何将参数从 python 脚本传递给方法 getContourResults() 存在于 io.c
【问题讨论】:
-
通常,
char**应指向以 NUL 结尾的char*s 数组的开头;你确定这里是否真的是这样吗? -
顺便说一句,这将很难测试答案,因为不是你的人不会有
erf_utils_io.dll。在标准库实用程序之间找到可比较的调用约定并围绕它构建minimal reproducible example 通常是获得更好结果的途径,因此回答您的问题的人将能够实际测试他们的答案(以及对这些答案进行判断和投票的人,同样)。 -
Python 不能直接调用这样的函数。您将需要创建一个包装函数,该函数公开与Python's C API 一致的接口以适应您的目标函数。您可以在 C 中直接将这样的包装器写入 C API,或者您也应该能够在 Cython 中编写它,这更像 Python。
-
前两个参数是
getContourResults是c_char_p,c_char_p不是POINTER(c_char_p),POINTER(c_char_p)。