//#include //#include //5.模块函数static PyObject* func1(PyObject* self, PyObject * args){ //返回pyth_编译c++为python包">
当前位置:   article > 正文

C++代码生成python扩展库案例_编译c++为python包

编译c++为python包

代码

func1modext.cpp

#include "Python.h"
//#include <opencv2\highgui\highgui.hpp>
//#include <opencv2\imgproc\imgproc.hpp>
//#include <opencv2/imgproc/types_c.h>


//5.模块函数
static PyObject* func1(PyObject* self, PyObject * args)
{
	//返回python的Long整形,c语言中引用计数加1,返回值交由python释放
	/*
	int i;
    dobule d;
    char *s;
    if(!PyArg_ParseTuple(args, "ids", &i, &d, &s))
    {
        return NULL;
    }
	*/
	/*
	    int a;
    int b;
    if(!PyArg_ParseTuple(args, "ii", &a, &b))
    {
        return NULL;
    }
    return Py_BuildValue("i", a+b);
	*/
	return PyLong_FromLong(101);
}

//4.模块函数列表数组
static PyMethodDef func1mod_funcs[] = {
	{
		"func1",   //函数名称
		func1,    //函数指针
		METH_NOARGS,   //参数标识 无参数 //元组参数 METH_VARARGS //关键字参数METH_VARARGS|METH_KEYWORDS
		"test func1 function"   //函数说明 help(func1)
	},
	{0,0,0,0}
};

//3.模块定义
static PyModuleDef func1mod_module = {
	PyModuleDef_HEAD_INIT,
	"func1modext" ,		 //模块名
	"func1modext is test",			 //模块说明,通过help(模块名)
	-1,					//模块空间,子解释器调用,-1不使用
	func1mod_funcs		 //模块函数
};

//1.扩展库入口文件 PyInit_固定的开头,func1mod模块名
PyMODINIT_FUNC PyInit_func1modext(void)
{
	printf("PyInit_func1modext\n");
	//2.模块创建 参数:PyModuleDef
	return PyModule_Create(&func1mod_module);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

setup.py

# -*- coding:utf-8 -*-
from distutils.core import *

setup(
    name = "func1modext",  #打包文件名称
    version = "1.0",
    ext_modules = [Extension("func1modext", ["func1modext.cpp"])]
    )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

写完setup.py之后,在终端运行命令(注意要在你对应的python环境下运行):python setup.py install.然后在当前目录下生成一个build文件,里面有生成好的pyd文件(pyd文件名称里会多一个cp37-win32,生成的时候自动加上的,这个可以不用管,),pyd文件其实就是一个dll文件,只是把dll的后缀名改成了pyd。python setup.py install.命令就会把这个pyd文件拷贝到python环境下的第三方库目录,比如我的是F:/Python-3.7.0/Lib/site-packages,这样你的扩展库已经做好了,这样你就可以对它使用了。

testmod.py

# -*- coding:utf-8 -*-
print("Test func1 Module")
import func1modext
print(help(func1modext))  //help函数用于获取它的信息
print(func1modext.func1())
  • 1
  • 2
  • 3
  • 4
  • 5

扩展:

如果大家想深入理解,可以查看python的源码(PyObject结构分析和PyLongObject分析),在python源码中的include目录下,object.h等头文件中可以学习到。这里不深入讨论。
如果C++扩展库中需要调用第三方opencv库,相对来说比较麻烦的,你可以参考https://github.com/Algomorph/pyboostcvconverter这篇大神的工程代码,它的代码也是参考opencv源码的,可以去学习下。一般来说做扩展库的代码不要包含其他第三方的库不然实现起来比较麻烦。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/555704
推荐阅读
相关标签