如何使用Python cType初始化C++头文件中的结构变量?
我试图使用Python ctypes初始化.h头文件中的ExternalInputs\u add\u two结构。头文件是:如何使用Python cType初始化C++头文件中的结构变量?,python,ctypes,Python,Ctypes,我试图使用Python ctypes初始化.h头文件中的ExternalInputs\u add\u two结构。头文件是: typedef struct { int32_T Input; /* '<Root>/Input' */ int32_T Input1; /* '<Root>/Input1' */ } ExternalInputs_add_two;
typedef struct {
int32_T Input; /* '<Root>/Input' */
int32_T Input1; /* '<Root>/Input1' */
} ExternalInputs_add_two;
什么ctypes函数初始化结构?到目前为止,我的Python代码是:
class ModelOutput(Structure):
_fields_ = [("Output", c_int)]
class ModelInput(Structure):
_fields_ = [("Input", c_int),
("Input1", c_int)]
#define the functions
initiateModel = cdll.add_two_win32.add_two_initialize
stepModel = cdll.add_two_win32.add_two_step
terminateModel = cdll.add_two_win32.add_two_terminate
#define the pointers to the functions
initiateModel.restype = c_void_p
stepModel.restype = c_void_p
terminateModel.restype = c_void_p
#initialize the model with value of 1
print "\n\nInitialize"
errMsg = initiateModel(1)
print "initateModel reports:", errMsg
#Set the input
test_input = ModelInput(1,2)
input_ptr = pointer(test_input)
#This probably doesn't work since ExternalInputs_add_two is a structure, not a function.
cdll.add_two_win32.ExternalInputs_add_two = input_ptr
#Get the output pointer from add_two_U
output = POINTER(ModelOutput)
results = output.in_dll(cdll.add_two_win32,"add_two_U")
print "got results", results.Output
昨天我问了一个问题,如何从成员add_two_获得输出。David昨天很好地回答了这个问题,使用in_dll函数
我在ctypes文档和在线搜索了使用ctypes设置结构的示例或函数。到目前为止我还没有找到
谢谢你的帮助
谢谢你的帮助和回答。不幸的是,以这种方式设置输入结构不起作用。我忘了提到一个Matlab脚本是为使用dll编写的,它可以正常工作。我正在尝试转换为Python。为了初始化结构ExternalInputs\u add\u two,Matlab使用以下语句:
sm.Input = 1
sm.Input1 = 2
sp = libpointer('ExternalInputs_add_two', sm)
然后调用add_two_函数:
sp = calllib('add_two_win32', 'add_two_U')
sp.value
get(sp, 'Value')
sp.Value.Input = 3
sp.Value.Input1 = 2
如果删除初始化ExternalInputs\u add\u two结构的Matlab语句,就会得到一个错误
初始化结构的Python ctypes等价于什么?如果我看起来是个讨厌的人,我很抱歉。你似乎把结构定义和结构实例混淆了。正如在头文件中声明的,ExternalInputs\U add\U two是一个类型,add\U two\U是一个实例。DLL不导出类型,只导出类型的实例。因此,Python代码中的以下行是毫无意义的:
cdll.add_two_win32.ExternalInputs_add_two = input_ptr
您可能希望改为修改名为add_two_的ExternalInputs_add_two的实例。要执行此操作,请按照David先前的回答建议执行,并使用in_dll函数:
PModelInput= POINTER(ModelInput)
padd_two_U = PModelInput.in_dll(cdll.add_two_win32, "add_two_U")
# Now modify the contents of the "add_two_U" variable
padd_two_U.Input = 1
padd_two_U.Input2 = 2
我的建议是停止从DLL导出变量。相反,您应该从DLL中导出两个函数:一个用于读取变量,另一个用于写入变量。谢谢您的回答,但是通过add\U two初始化ExternalInputs\U add\U two\U不起作用。使用C++接口功能的MATLAB脚本是有效的。为了初始化输入结构,Matlab使用以下语句:
PModelInput= POINTER(ModelInput)
padd_two_U = PModelInput.in_dll(cdll.add_two_win32, "add_two_U")
# Now modify the contents of the "add_two_U" variable
padd_two_U.Input = 1
padd_two_U.Input2 = 2