使用Pybind11将c++第三方库编译为动态链接库

  1. 首先编写一个cpp文件,名字为"add_func.cpp",内容如下:
cpp 复制代码
#include <pybind11/pybind11.h>
#include <iostream>

namespace py = pybind11;
int add(int i, int j){
    return i+j;
}

void inadd(){
    int a, b;
    std::cin>>a>>b;
    std::cout<<a+b;
}

PYBIND11_MODULE(add_func, m){
    m.doc() = "pybind11 example plugin";
    m.def("add", &add, "A function which adds two numbers");
    m.def("inadd", &inadd, "cin and cout");
}
  1. 在终端输入:
bash 复制代码
c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) add_func.cpp -o add_func$(python3-config --extension-suffix)

编译完成后,该文件夹下就会出现一个名为add_func.cpython-39-x86_64-linux-gnu.so的文件夹

  1. 此时在该文件夹下打开终端,输入python
python 复制代码
import add_func

add_func(1, 2)

此时终端就会打印出3

相关推荐
金銀銅鐵2 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li4 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
见过夏天7 小时前
C++ 基础入门完全指南
c++
小九九的爸爸8 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学9 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry