Python 调用 C++

本文介绍如何使用Boost.Python库将C++代码封装为Python可调用的函数及类,包括基本函数、带默认参数的函数、类及STL容器的封装方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.open-open.com/lib/view/open1329532323890.html

换句话说,就是需要把C++封装成Python可以“理解”的类型。通过使用C++实现测试激励的内部逻辑,然后Python调用C++的这个实现函数即可,这样可以大大减轻脚本编写的速度以及复杂度。

#include <boost/python.hpp> 
#include <boost/python/module.hpp> 
#include <boost/python/def.hpp> 
#include <boost/python/to_python_converter.hpp> 
#include 
using namespace std; 
using namespace boost::python;


namespace HelloPython{ 
// 简单函数 
char const* sayHello(){ 
    return "Hello from boost::python"; 
}


// 简单类 
class HelloClass{ 
public: 
    HelloClass(const string& name):name(name){ 
    } 
public: 
    string sayHello(){ 
      return "Hello from HelloClass by : " + name; 
    } 
private: 
    string name; 
}; 
// 接受该类的简单函数 
string sayHelloClass(HelloClass& hello){ 
    return hello.sayHello() + " in function sayHelloClass"; 
}


//STL容器 
typedef vector<int> ivector;


//有默认参数值的函数 
void showPerson(string name,int age=30,string nationality="China"){ 
    cout << name << " " << age << " " << nationality << endl; 
}


// 封装带有默认参数值的函数 
BOOST_PYTHON_FUNCTION_OVERLOADS(showPerson_overloads,showPerson,1,3) //1:最少参数个数,3最大参数个数


// 封装模块 
BOOST_PYTHON_MODULE(HelloPython){ 
    // 封装简单函数 
    def("sayHello",sayHello);

    // 封装简单类,并定义__init__函数 
    class_("HelloClass",init()) 
      .def("sayHello",&HelloClass::sayHello)//Add a regular member function 
      ; 
    def("sayHelloClass",sayHelloClass); // sayHelloClass can be made a member of module!!!


    // STL的简单封装方法 
    class_("ivector") 
      .def(vector_indexing_suite()); 
    class_ >("ivector_vector") 
      .def(vector_indexing_suite >());


    // 带有默认参数值的封装方法 
    def("showPerson",showPerson,showPerson_overloads()); 
}

Python调用C++代码可以通过多种方法实现,主要包括使用扩展模块、C/C++接口封装以及工具链辅助生成绑定代码等方式。以下是几种常见且实用的方案: ### 1. 使用 `ctypes` 调用 C 风格共享 虽然 `ctypes` 主要用于调用 C 编写的动态链接(如 `.so` 或 `.dll`),但可以通过将 C++ 代码编译为具有 `extern "C"` 导出符号的共享来间接调用 C++ 函数。 ```cpp // hello.cpp #include <iostream> extern "C" { void greet() { std::cout << "Hello from C++!" << std::endl; } } ``` 编译为共享: ```bash g++ -shared -fPIC -o libhello.so hello.cpp ``` 然后在 Python调用: ```python import ctypes lib = ctypes.CDLL('./libhello.so') lib.greet() ``` ### 2. 使用 `Boost.Python` 创建 Python 扩展 `Boost.Python` 是一个功能强大的,允许你直接将 C++ 类和函数暴露给 Python。它需要安装 Boost 并进行适当的配置。 ```cpp // example.cpp #include <boost/python.hpp> char const* greet() { return "Hello from C++ with Boost.Python!"; } BOOST_PYTHON_MODULE(example) { using namespace boost::python; def("greet", greet); } ``` 编译命令示例: ```bash g++ -I/usr/include/python3.8 -I/usr/local/include/boost -fPIC -shared example.cpp -o example.so -lboost_python38 -lpython3.8 ``` 然后在 Python 中导入并使用: ```python import example print(example.greet()) ``` ### 3. 使用 `pybind11` 构建轻量级绑定 `pybind11` 是一个现代、轻量级的头文件,专为简化 C++Python 的交互而设计,推荐用于新项目。 ```cpp // main.cpp #include <pybind11/pybind11.h> int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m) { m.def("add", &add, "A function that adds two numbers"); } ``` 编译命令(确保已安装 pybind11): ```bash c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) main.cpp -o example$(python3-config --extension-suffix) ``` Python 中使用: ```python import example print(example.add(3, 4)) # 输出 7 ``` ### 4. 使用 SWIG 自动生成绑定代码 SWIG 是一个自动包装器生成工具,支持多种语言,包括 PythonC++。适用于已有大型 C++ 项目希望快速暴露接口Python 的场景。 假设有一个 `example.i` 接口定义文件: ```swig %module example %{ #include "example.h" %} int add(int a, int b); ``` 对应的 `example.h` 和 `example.cpp` 实现了 `add` 函数。使用 SWIG 生成绑定代码后,再编译为 Python 模块即可调用。 --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值