2011-03-23 131 views
0

我想从使用ctypes的Python调用C++函数add_two_U。功能add_two_U在C++头文件中定义为:如何使用没有输入参数的ctypes调用函数?

extern ExternalInputs_add_two add_two_U; 

结构ExternalInputs_add_two在头文件中定义为:

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

功能add_two_initialize我在下面我的Python代码中调用被定义在头文件为:

extern void add_two_initialize(boolean_T firstTime); 

我的Python代码:

import sys 
from ctypes import * 

class ModelInput(Structure): 
    _fields_ = [("Input", c_int), 
       ("Input1", c_int)] 

#define the functions  
initiateModel = cdll.add_two_win32.add_two_initialize 
U_Model = cdll.add_two_win32.add_two_U 


# define the pointers to the functions 
initiateModel.restype = c_void_p 
U_Model.restype = c_void_p 

#initialize the model with value of 1 
print "\n\nInitialize" 
errMsg = initiateModel(1) 
print "initateModel reports:", errMsg 

#Initialize the structure and get the pointer. 
test_input = ModelInput(1,2) 
input_ptr = pointer(test_input) 

我想通过变量U_Model在python代码中调用函数add_two_U。请注意,头文件中此函数没有任何输入参数,并使用头文件中的结构来获取输入数据。

我有以下2个问题:

  1. 如何设置在我的Python代码结构ExternalInputs_add_two结构将数据传递到add_two_U功能?

  2. 如何在Python代码中通过U_Model引用无参数add_two_U的dll函数?如果我使用Python语句来调用函数:

    result = U_Model() 
    

    我得到以下错误:

    WindowsError: exception: access violation reading 0xFFFFFFFF 
    

我搜索上线的答案,但没有找到一个在头文件中初始化结构并调用没有参数的函数的示例。

请注意,在我的Python代码中,由于此函数具有输入参数,因此我可以调用函数add_two_initialize thru initModel而无错误。

回答

1

add_two_U不是一个函数,它是一个导出的值。您需要使用in_dll

请参阅Accessing values exported from dlls

+0

@斯科特我从你的另一个问题看,这似乎是你的答案。请你可以这样标记它,点击这个答案旁边的勾号使它变绿。请阅读有关所有细节的常见问题解答。 – 2011-03-25 13:42:00

0

David,

谢谢你回答我的第一个问题。我将我的Python代码更改为:

#Comment out this line. add_two_U is not a function 
#U_Model = cdll.add_two_win32.add_two_U 

#Get the output pointer from add_two_U 
output = POINTER(ModelInput) 
results = output.in_dll(cdll.add_two_win32,"add_two_U") 

print "got results", results.contents() 

此代码有效。我仍然无法弄清楚我的第一个问题的答案:如何设置从Python代码的头文件中初始化ExternalInputs_add_two结构。

我搜查了ctypes文档,找不到函数或示例如何执行此操作。我意识到它可能在文档中。

+0

此空间仅供解答您的问题。您应该编辑您的原始问题以添加其他信息。 – 2011-03-25 01:11:10

相关问题