从python中的dll函数返回结构时出错

2024-04-16 23:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用C写的dll导出这个函数:

typedef struct testResult_t {
    int testId;
    int TT; 
    double fB;
    double mD;
    double mDL;
    int nS;
    int nL;
} TestResult;

TestResult __stdcall dummyTest(){
    TestResult a = {0};
    a.testId = 3;
    return a;
};

我从python调用函数的方式是:

^{pr2}$

我在执行脚本时遇到此错误:

Traceback (most recent call last):
  File "ast.py", line 330, in <module>
    main()
  File "ast.py", line 174, in main
    result = astdll.dummyTest()
  File "_ctypes/callproc.c", line 941, in GetResult
TypeError: an integer is required

知道有什么问题吗?在


Tags: 函数inpymainlineaststructfile
1条回答
网友
1楼 · 发布于 2024-04-16 23:22:27

抱歉,我无法重现您的问题(Windows 7 x64,32位Python 2.7.3)。我将描述我为重现你的问题所做的努力,希望能对你有所帮助。在

<>我在Visual C++ Express 2008中创建了一个新项目和解决方案,都被命名为“CDLL”。项目被设置为编译为C代码并使用stdcall调用约定。除了VC++2008自动生成的内容外,它还有以下两个文件:

CDll.h:

#ifdef CDLL_EXPORTS
#define CDLL_API __declspec(dllexport) 
#else
#define CDLL_API __declspec(dllimport) 
#endif

typedef struct testResult_t {
    int testId;
    int TT; 
    double fB;
    double mD;
    double mDL;
    int nS;
    int nL;
} TestResult;

TestResult CDLL_API __stdcall dummyTest();

在CDll.cpp公司(是的,我知道扩展名是“.cpp”,但我认为这不重要):

^{pr2}$

然后我编译并构建了DLL。然后,我尝试加载它并使用以下Python脚本调用函数:

from ctypes import Structure, c_int, c_double, windll

astdll = windll.CDll

class TestResult(Structure):
    _fields_ = [
        ("testId", c_int),
        ("TT", c_int),
        ("fB", c_double),
        ("mD", c_double),
        ("mDL", c_double),
        ("nS", c_int),
        ("nL", c_int)
    ]

astdll.dummyTest.restype = TestResult
result = astdll.dummyTest()
print "Test ID: %d" % (result.testId)

当我运行这个脚本时,我得到了输出Test ID: 3。在


我对您可能出现的问题的第一个想法是,您试图使用CDLL加载DLL,而您应该使用windll,但是当我尝试使用CDLL时,我得到了一个完全不同的错误消息。您没有向我们展示如何加载DLL,但我怀疑您使用的是windll,正如我上面所做的那样。在

相关问题 更多 >