【发布时间】:2011-03-23 15:30:21
【问题描述】:
我正在尝试使用 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。注意在头文件中,这个函数没有任何输入参数,并使用头文件中的结构来获取输入数据。
我有以下 2 个问题:
如何在我的 Python 代码中设置结构 ExternalInputs_add_two 结构以将数据传递给
add_two_U函数?-
如何调用没有参数
add_two_U的dll 函数,我在Python 代码中通过U_Model引用了该函数?如果我使用 Python 语句调用函数:result = U_Model()我收到以下错误:
WindowsError: exception: access violation reading 0xFFFFFFFF
我在网上搜索了答案,但找不到在头文件中初始化结构并调用不带参数的函数的示例。
请注意,在我的 Python 代码中,我可以通过initialModel 调用函数 add_two_initialize 且没有错误,因为该函数具有输入参数。
【问题讨论】: