我很清楚 C++ 没有标准 ABI,所以这就是我所做的:
//trialDLL.h
#ifndef TRIALDLL_H_
#define TRIALDLL_H_
class MyMathFuncs
{
private:
double offset;
public:
MyMathFuncs(double offset);
~MyMathFuncs();
double Add(double a, double b);
double Multiply(double a, double b);
double getOffset();
};
#ifdef __cplusplus
extern "C"{
#endif
#ifdef TRIALDLL_EXPORT
#define TRIALDLL_API __declspec(dllexport)
#else
#define TRIALDLL_API __declspec(dllimport)
#endif
TRIALDLL_API MyMathFuncs* __stdcall new_MyMathFuncs(double offset);
TRIALDLL_API void __stdcall del_MyMathFuncs(MyMathFuncs *myMath);
TRIALDLL_API double __stdcall MyAdd(MyMathFuncs* myMath, double a, double b);
#ifdef __cplusplus
}
#endif
#endif
以及.cpp的定义:(其他类函数的定义省略)
//trialDLL.cpp
#include "trialDLL.h"
MyMathFuncs* __stdcall new_MyMathFuncs(double offset)
{
return new MyMathFuncs(offset);
}
void __stdcall del_MyMathFuncs(MyMathFuncs *myMath)
{
myMath->~MyMathFuncs();
}
double __stdcall MyAdd(MyMathFuncs *myMath, double a, double b)
{
return myMath->Add(a, b);
}
// class functions
double MyMathFuncs::Add(double a, double b)
{
return a+b+ this->offset;
}
我将它构建成一个 dll 并将其命名为 trialDLL3.dll。然后在python中,我写了一个模块:
#trialDLL3.py
import ctypes
from ctypes import WinDLL
class MyMath(object):
def __init__(self, offset):
self.FunMath = WinDLL('trialDLL3.dll')
self.FunMath.new_MyMathFuncs.argtypes = [ctypes.c_double]
self.FunMath.new_MyMathFuncs.restype = ctypes.c_void_p
self.FunMath.MyAdd.argtypes = [ctypes.c_void_p, \
ctypes.c_double, ctypes.c_double]
self.FunMath.MyAdd.restype = ctypes.c_double
self.obj = self.FunMath.new_MyMathFuncs(offset)
def FunAdd(self, a, b):
self.FunMath.MyAdd(self.obj, a, b)
def delete():
self.FunMath.del_MyMathFuncs()
在这一切之后,奇怪的事情发生了。在 IDLE python shell 中,我做了:
theMath = MyMath(3.3) #create the instance
theMath.FunAdd(3.3, 3.3) #call the function
第二行返回 None 而不是 9.9。然后我尝试了另一种方式,将这一行放入外壳中:
theMath.FunMath.MyAdd(theMath.obj, 3.3 ,3.3)
这条线返回给我的 9.9 并不令人惊讶,但与上一个结果 None 相比却令人惊讶。这两行不应该相同吗?我决定在 python shell 中显式运行所有这些行,看看会出现什么问题,写:(不包括导入)
loadedDLL = WinDLL('trialDLL3.dll')
loadedDLL.new_MyMathFuncs.argtypes = [ctypes.c_double]
loadedDLL.new_MyMathFuncs.restype = ctypes.c_void_p
loadedDLL.MyAdd.argtypes = [ctypes.c_void_p, \
ctypes.c_double, ctypes.c_double]
loadedDLL.MyAdd.restype = ctypes.c_double
obj = loadedDLL.new_MyMathFuncs(3.3)
FunMath.MyAdd(obj, 3.3, 3.3)
所有这些行最终返回 9.9。如果 trialDLL3.py 模块被导入,这些行不是与这两行相同吗?
theMath = MyMath(3.3) #create the instance
theMath.FunAdd(3.3, 3.3) #call the function
如果它们是相同的交易,为什么两行类版本返回 None 而显式方式返回预期的 9.9?提前致谢!