使用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

相关推荐
薛定e的猫咪2 分钟前
【调试技巧】vscode 四种断点调试,快速定位 bug
ide·vscode·python·bug
CadeCode3 分钟前
Python 开发环境与包管理
python
b***74888 分钟前
PHP在电子商务系统中的构建
开发语言·php
爱写代码的小朋友18 分钟前
Python局域网远程监控电脑屏幕实现
python·flask·python监控电脑屏幕
岚天start18 分钟前
Java程序生成Heap Dump堆内存快照文件的多种方法
开发语言·python·pycharm
兆。21 分钟前
python全栈-人工智能基础-机器学习
人工智能·python·机器学习
天马行空-33 分钟前
ES 精准匹配 和 模糊查询的实现方式
java·开发语言
深度学习lover40 分钟前
<项目代码>yolo遥感航拍船舶识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·遥感船舶识别
Z***258042 分钟前
Java计算机视觉
java·开发语言·计算机视觉
Tiger_shl1 小时前
SqlConnection、SqlCommand 和 SqlDataAdapter
开发语言·数据库·c#