python封装和调用_如何将C++的API封装成python可调用形式?

个人觉得boost是最爽的方式。cython虽然速度不错,但是很多时候是要重新实现代码的。boost可以直接调用c++/C代码。

概述

有不同的方法来用C++扩展Python:Swig

使用Boost.Python,可选择使用Py++预处理

使用Cython。

Cython出现之前,Boost.Python是编写C ++扩展模块最爽的方式。

Boost.Python集成在Boost C++ Libraries中。 要在Ubuntu系统上安装;

$ sudo apt-get install libboost-python-dev

$ sudo apt-get install python-dev

快速入门

hellomodule.cpp

#include

using namespace std;

void say_hello(const char* name) {

cout << "Hello " << name << "!\n";

}

#include

#include

using namespace boost::python;

BOOST_PYTHON_MODULE(hello)

{

def("say_hello", say_hello);

}

setup.py

#!/usr/bin/env python

# 技术支持qq群: 144081101 591302926 567351477

from distutils.core import setup

from distutils.extension import Extension

setup(name="PackageName",

ext_modules=[

Extension("hello", ["hellomodule.cpp"],

libraries = ["boost_python"])

])

编译:

python2.7 setup.py build

running build

running build_ext

building 'hello' extension

creating build/temp.linux-x86_64-2.7

x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-nbjU53/python2.7-2.7.15~rc1=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c hellomodule.cpp -o build/temp.linux-x86_64-2.7/hellomodule.o

cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++

creating build/lib.linux-x86_64-2.7

x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-nbjU53/python2.7-2.7.15~rc1=. -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-nbjU53/python2.7-2.7.15~rc1=. -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/hellomodule.o -lboost_python -o build/lib.linux-x86_64-2.7/hello.so

执行:

$ python2.7

Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34)

[GCC 7.3.0] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> import hello

>>> hello.say_hello("World")

Hello World!

python3怎么办?

参考下原文

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值