如何使用Python cType初始化C++头文件中的结构变量?

2024-10-04 11:33:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用Python ctypes初始化.h头文件中的ExternalInputs_add_two结构。头文件是:

typedef struct {  
    int32_T Input;                       /* '<Root>/Input' */  
    int32_T Input1;                      /* '<Root>/Input1' */  
} ExternalInputs_add_two;  

我需要初始化此结构,因为此成员声明使用结构值作为输入:

^{pr2}$

什么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_U获取输出。David昨天很好地回答了这个问题(使用in_dll函数)。在

我已经在ctypes文档和在线文档中搜索了一个使用ctype设置结构的示例或函数。到目前为止我还没有找到。在

谢谢你的帮助。在

谢谢你的帮助和回答。不幸的是,以这种方式设置输入结构是行不通的。我忘了提到一个Matlab脚本是用来使用dll的,它可以工作。我正在尝试转换成Python。为了初始化ExternalInputs_add_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_add_two结构的Matlab语句,就会得到一个错误。在

初始化结构的Python ctypes等价于什么?如果我看起来像个害虫,我很抱歉。在


Tags: the函数addinputctypes结构spint
2条回答

似乎你混淆了结构定义和结构实例。正如头文件中声明的,ExternalInputs_add_two是一个类型,而add_two_U是一个实例。DLL不导出类型,只导出类型的实例。因此,Python代码中的以下行是没有意义的:

cdll.add_two_win32.ExternalInputs_add_two = input_ptr

相反,您可能希望修改名为ExternalInputs_add_two实例。为此,请按照David之前的回答建议进行操作,并使用in_dll函数:

^{pr2}$

我给你的建议是停止从DLL导出变量。相反,您应该从DLL中导出两个函数:一个用于读取变量,另一个用于写入变量。在

相关问题 更多 >