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

时间:2013-05-07 18:21:04

标签: python function dll structure ctypes

我有一个用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调用函数:

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)

执行脚本时出现此错误:

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

任何想法是什么问题?

1 个答案:

答案 0 :(得分:0)

抱歉,我无法重现您的问题(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',但我认为不重要):

#include "stdafx.h"
#include "CDll.h"

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

然后我编译并构建了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时尝试使用windll加载DLL,但当我尝试使用CDLL时,我得到了一个完全不同的错误信息。您还没有向我们展示如何加载DLL,但我怀疑您正在使用windll,如上所述。