python3 C++扩展

0、环境

  1. Anaconda3-2020.02-Windows-x86_64(Python 3.7.6 )
  2. opencv_python-4.4.0.40-cp37-cp37m-win_amd64.whl(可选)
  3. VS2012

1、找不到inttypes.h

在VS 2012中编译会报inttypes.h错误,可以直接在C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include 目录下新建inttypes.h文件,文件内容如下:

#pragma once
#include 

2、找不到Py_InitModule()

网上例子是在python2环境下,python3已经弃用该方法,具体使用可参考官方文档,根据网上例子python c 扩展 ctype 以及 效率对比稍作修改。

#include 

static PyObject *
spam_add(PyObject * self,PyObject *args)
{
    long a;
    //将python中传入的变量转化成C中的变量
    if(!PyArg_ParseTuple(args,"l",&a))
        return NULL;
    long long tmp=0;
    for(long i = 1;i<=a;i++)
        tmp +=i;
    //将C中的变量转化成python中的变量
    return Py_BuildValue("L",tmp);
}
 
//方法定义
static PyMethodDef SpamMethods[] = {
     //每个方法都有四个属性
     //分别为 1、python中方法名 2、c中名称
     //3、应该就是传入的参数
     //4、方法描述
    {"add",spam_add,METH_VARARGS,"Return the cumulative value "},
    //这个是必须加的,应该都一样吧
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

static struct PyModuleDef SpamModule = {
    PyModuleDef_HEAD_INIT,
    "IRCam",
    NULL,
    -1,
    SpamMethods
};

//初始化模块
//PyInit_IRCamDll名称  必须跟 IRCamDll库文件名称关联
//可以如下测试:
//import spam 
//dir(spam)
PyMODINIT_FUNC
PyInit_IRCamDll(void)
{
    return PyModule_Create(&SpamModule);
}

3、链接无法打开python37_d.lib错误

这个是debug库,环境没自带,那就把C++工程用release编译吧!

4、对象扩展

前面只是扩展了C函数,下面代码实现扩展类对象,结构体类型类似,通过PyCapsule_New、PyCapsule_GetPointer实现。
C++代码

#include 


class CamCapture
{
public:
    ~CamCapture(){printf("~CamCapture\r\n");}
    CamCapture(int first, double second) 
        : m_first( first), m_second(second){printf("CamCapture()\r\n");}

    double Test1(void){ return m_first*m_second;}
private:
    int m_first;
    double m_second;
};

static void PyDelCamCaptureDetector(PyObject *obj)
{
    printf("CameraCapture_UnInit\n");
    CamCapture * tmp = (CamCapture *) PyCapsule_GetPointer(obj, "CamCapture");
    delete tmp;

    return;
}
PyObject *CamCapture_Init(PyObject *, PyObject* args)
{
    int arg1;
    double arg2;
    printf("CameraCapture_Init\n");
    int ok = PyArg_ParseTuple(args,"id",&arg1,&arg2);
    if(!ok) return NULL;

   //动态创建一个新对象
    CamCapture *camCapture = new CamCapture(arg1, arg2);

   //把指针camCapture包装成PyCObject对象并返回给解释器
    return PyCapsule_New(camCapture, "CamCapture", PyDelCamCaptureDetector);
    //PyCapsule_New(camCapture, "CamCapture", must_free ? PyDelCamCaptureDetector : NULL);
    //return PyCObject_FromVoidPtr(camCapture, PyDelCamCaptureDetector);
}

PyObject * CamCapture_Test1(PyObject *, PyObject* args)
{
    PyObject *pyobj = 0;
    int ok = PyArg_ParseTuple( args, "O", &pyobj);
    if(!ok) return NULL;
   //把PyCObject转换为void指针

   // void * temp = PyCObject_AsVoidPtr(pyobj);
    void * temp = (CamCapture *) PyCapsule_GetPointer(pyobj, "CamCapture");
   //把void指针转换为一个CamCapture对象指针

    CamCapture *camCapture = static_cast(temp);
    //调用函数

    double result = camCapture->Test1();
    //返回结果 
    
    return Py_BuildValue("d",result);
}

PyObject * CamCapture_Test2(PyObject *, PyObject* args)
{
    
    return Py_BuildValue("(is)",5,"V5");
}

static PyMethodDef DllMethods[] = {
    {"CamCapture", CamCapture_Init, METH_VARARGS, "Init"},
    {"Test1", CamCapture_Test1, METH_VARARGS, "Test1"},
    {"Test2", CamCapture_Test2, METH_VARARGS, "Test2"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef DllModule = {
    PyModuleDef_HEAD_INIT,
    "IRCam",//name of module
    NULL,//module documentation, may be NULL
    -1,//size of per-interpreter state of the module, or -1 if the module keeps state in global variables.
    DllMethods
};

//初始化模块
//PyInit_IRCamDll名称  必须跟 IRCamDll库文件名称关联
PyMODINIT_FUNC
PyInit_IRCamDll(void)
{
    return PyModule_Create(&DllModule);
}

python测试代码

from IRCamDll import *

class IRCam(object):
    def __init__(self,arg1,arg2):
        self._base = CamCapture(arg1,arg2)
    def Test1(self):
        return Test1(self._base)
    def Test2(self):
        return Test2(self._base)
        

obj = IRCam(2, 100)
print(obj.Test1())
print(obj.Test2())
ri,rs = obj.Test2()
print(ri + 1)
print(rs + "V6")

obj1 = IRCam(4, 1000)
print(obj1.Test1())
print(obj1.Test2())

A、参考资料

Python C++扩展
python扩展之C++篇
windows下python调用C/C++以及使用C扩展python
Python的C/C++扩展
Python/c Api 扩展解析
『Python CoolBook』C扩展库其四结构体操作与Capsule

你可能感兴趣的:(python3 C++扩展)