python调用C++
python调用C++的方法有很多,笔者也试了很多但是不太好用
今天看到有人用swig来做封装
安装swig
$ sudo apt-get install swig
源文件
//test.h
int add(int a,int b);
int sub(int a,int b);
//test.cpp
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
test.i
//%module 后面的名字是被封装的模块名称。封装口,python通过这个名称加载程序
//%{ %}之间所添加的内容,一般包含此文件需要的一些函数声明和头文件。
//最后一部分,声明了要封装的函数和变量,直接使用%include 文件模块头文件直接包含即可
//file test.i
%module test
%{
#include "test.h"
%}
%include "test.h"
执行命令编译.i文件
$ swig -python -c++ test.i
此时会生成对应的文件: 模块名_warp.cxx、模块名.py
利用python提供的自动化编译模块进行编译。编写一个编译文件setup.py
# setup.py
"""
setup.py file for SWIG example
"""
from distutils.core import setup, Extension
import numpy
test_module = Extension('_test', # #模块名称,必须要有下划线"_"必须有
sources=['test_wrap.cxx', 'test.cpp'], #封装的cxx和源文件cpp
)
setup(name = 'test', #打包后的名称
version = '0.1',
author = "zhangbo",
description = """Simple swig example from docs""",
ext_modules = [test_module], #与上面的扩展模块名称一致
py_modules = ["test"], #需要打包的模块列表
)
利用python的执行setup.py文件
$ python setup.py build #编译生成对应库,可供python直接调用的模块
实现过程如下所示:test模块为通过编译c++代码生成test模块,前面已经介绍c++代码示例:
import test
print(test.add(3, 4))
Inference
[1] https://blog.csdn.net/qq_26105397/article/details/83153606