从python中的dll函数返回结构时出错
我有一个用C编写的dll导出此函数:从python中的dll函数返回结构时出错,python,function,dll,structure,ctypes,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
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
回溯(最近一次呼叫最后一次):
文件“ast.py”,第330行,在
main()
文件“ast.py”,第174行,主
结果=astdll.dummyTest()
文件“\u ctypes/callproc.c”,第941行,在GetResult中
TypeError:需要一个整数
知道问题出在哪里吗?对不起,我无法重现您的问题(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”,但我认为这无关紧要):
然后我编译并构建了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)
当我运行这个脚本时,我得到了输出测试ID:3
我对您的问题的第一个想法是,当您应该使用
windl
时,您试图使用CDLL
加载DLL,但当我尝试使用CDLL
时,我收到了一条完全不同的错误消息。您没有向我们展示如何加载DLL,但我怀疑您正在使用windle
,正如我在上面所做的那样。您应该展示所有内容。你遗漏了重要的细节。我们看不到什么是astdll
。一个更大的问题是,不同的C编译器有不同的ABI来返回大型结构。值得注意的是,MSVC和GCC对您的函数有不同的ABI。使用引用参数ctypes.byref返回结构是设计此接口的最佳方法。这就是问题所在,我使用oledll加载库。非常感谢@Jorge请注意,您的函数只能从使用MS large struct返回值ABI的编译器中调用。Luke,您能看看我的问题吗?这是一个非常相似的问题,不同的是我的结构中有字符串,这让我头痛好几天
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)