如何使用没有输入参数的ctypes调用函数?

时间:2011-03-23 15:30:21

标签: python ctypes

我试图使用ctypes从Python调用C ++函数add_two_U。函数add_two_U在C ++头文件中定义为:

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;

我在下面的Python代码中调用的函数add_two_initialize在头文件中定义为:

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。请注意,在头文件中,此函数没有任何输入参数,并使用头文件中的结构来获取输入数据。

我有以下两个问题:

  1. 如何在Python代码中设置结构ExternalInputs_add_two结构以将数据传递给add_two_U函数?

  2. 如何在没有参数add_two_U的情况下调用dll函数,我在Python代码中引用U_Model?如果我使用Python语句来调用函数:

    result = U_Model()
    

    我收到以下错误:

    WindowsError: exception: access violation reading 0xFFFFFFFF
    
  3. 我在线搜索了一个答案,找不到在头文件中初始化结构并调用没有参数的函数的示例。

    请注意,在我的Python代码中,我能够通过initiateModel调用函数add_two_initialize而没有错误,因为此函数具有输入参数。

2 个答案:

答案 0 :(得分:1)

add_two_U不是函数,而是导出值。您需要使用in_dll

请参阅Accessing values exported from dlls

答案 1 :(得分:0)

大卫,

感谢您回答我的第一个问题。我将我的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文档,找不到有关如何执行此操作的函数或示例。我意识到它可能在文档中。