Python,使用ctypes创建C ++类包装器

时间:2013-04-28 21:32:29

标签: python c dll ctypes

我很清楚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。然后我尝试了另一种方法,将这一行放在shell中:

theMath.FunMath.MyAdd(theMath.obj, 3.3 ,3.3)

这一行给我带来了一个不足为奇的9.9,但与上一个结果相比却令人惊讶。这两条线不应该相同吗?我决定在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?提前谢谢!

1 个答案:

答案 0 :(得分:5)

一切正常......但是你忘了在MyMath.FunAdd方法中传递C函数的返回值!

def FunAdd(self, a, b):
    return self.FunMath.MyAdd(self.obj, a, b)
    ^^^^^^