【问题标题】:How to call functions using ctypes with no input parameters?如何使用没有输入参数的 ctypes 调用函数?
【发布时间】: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 个问题:

  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
    

我在网上搜索了答案,但找不到在头文件中初始化结构并调用不带参数的函数的示例。

请注意,在我的 Python 代码中,我可以通过initialModel 调用函数 add_two_initialize 且没有错误,因为该函数具有输入参数。

【问题讨论】:

    标签: python ctypes


    【解决方案1】:

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

    Accessing values exported from dlls

    【讨论】:

    • @Scott 我从您的其他问题中看到这似乎是您的答案。请您将其标记为这样,通过单击此答案旁边的勾号使其变为绿色。请阅读常见问题解答以了解所有详细信息。
    【解决方案2】:

    大卫,

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

    【讨论】:

    • 此空间仅供回答您的问题。您应该编辑原始问题以添加更多信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2021-03-21
    • 2020-03-16
    相关资源
    最近更新 更多