【问题标题】:Passing arguments to functions from a dll loaded with ctypes从加载了 ctypes 的 dll 向函数传递参数
【发布时间】:2016-01-28 17:38:24
【问题描述】:

我试图从我的 Python 代码中调用一个来自 dll 的简单函数,使用 QtCreator 构建,但问题是参数大小总是无效的。

这是我的 test.htest.cpp 为空):

#ifndef TEST_H
#define TEST_H

#include "test_global.h"

extern "C"
{

   int TESTSHARED_EXPORT si () { return sizeof(int);}

   int TESTSHARED_EXPORT add4 ( int i) { return i + 4;}
}


#endif // TEST_H

它构建为 test.dll,我可以加载它:

tdll = windll.LoadLibrary(r'X:\TMP\SRC\build-test-Desktop_Qt_5_1_1_MinGW_32bit-Release\release\test.dll')

调用print tdll.si() 会按预期打印 4, 但是对tdll.add4(1) 的所有调用都失败并出现错误:

Traceback (most recent call last):
  File "test.py", line 29, in <module>
    print tdll.add4(2)
ValueError: Procedure probably called with too many arguments (4 bytes in excess)

如果我将add4 参数包装成c_int, c_uint, c_int32 或ctypes 提供的任何其他*int 类型,也会发生同样的事情。

请帮我解决这个问题。 谢谢!

【问题讨论】:

    标签: python dll ctypes


    【解决方案1】:

    这些是调用约定不匹配的症状。可能您导出的函数是__cdecl,但您的ctypes 代码使用__stdcall。您的问题没有足够的信息让我确定这一点,但很可能并且确实解释了报告的行为。

    通过使用cdll 而不是windll 来解决不匹配问题。使用windll 会导致使用__stdcall,使用cdll 会导致使用__cdecl

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多