2013-05-07 26 views
2

返回结构我有一个DLL写在C出口这样的功能:错误从DLL函数在Python

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 

任何想法有什么问题?

+0

你应该显示一切。你已经省略了重要的细节。我们看不到'astdll'是什么。更大的问题是不同的C编译器对于返回大型结构体有不同的ABI。值得注意的是MSVC和GCC对你的功能有不同的ABI。使用引用参数ctypes.byref返回结构是设计此接口的最佳方法。 – 2013-05-08 02:47:30

回答

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',但我不” t认为重要):

#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,正如我上面所做的那样。

+0

这是问题所在,我正在使用oledll加载库。非常感谢你!! – Jorge 2013-05-08 08:19:48

+0

@Jorge请注意,你的函数只能从使用MS大结构返回值ABI的编译器中调用。 – 2013-05-08 12:30:07

+0

卢克,请你看看我的问题[链接](http://stackoverflow.com/questions/20773602/returning-struct-from-c-dll-to-python)?这是非常类似的问题,不同的是我在我的结构中有字符串,它让我头痛几天 – Aleksandar 2013-12-25 14:36:24