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

0 投票
2 回答
1754 浏览
提问于 2025-04-16 14:16

我正在尝试通过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. 我该如何调用没有参数的dll函数add_two_U,这个函数在Python代码中通过U_Model引用?如果我用Python语句调用这个函数:

    result = U_Model()
    

    我会得到以下错误:

    WindowsError: exception: access violation reading 0xFFFFFFFF
    

我在网上搜索过答案,但找不到初始化头文件中的结构体和调用没有参数的函数的例子。

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

2 个回答

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的文档,但找不到相关的函数或示例来说明该怎么做。我知道这可能在文档里。

1

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

可以查看 从dll中访问导出的值

撰写回答