日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/19 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c调用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怎么辦?

參考下原文

總結

以上是生活随笔為你收集整理的c调用python打包_如何将C++的API封装成python可调用形式?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。