pybind11案例

本文介绍了如何使用pybind11创建C++模块与Python集成,并通过CMake进行构建。步骤包括编写example.cpp和CMakeLists.txt,构建so文件,以及在Python中导入并调用C++函数。
摘要由CSDN通过智能技术生成

example.cpp和CMakeLists.txt放在test文件夹下面,然后在test文件夹里新建一个build文件夹,运行cmake ..make,随后会生成一个example.cpython-37m-x86_64-linux-gnu.so文件,随后将a.py放在build路径下,运行python3 a.py
example.cpp

#include <iostream>
#include <pybind11/pybind11.h>
namespace py = pybind11;
using namespace std;

int add(int a, int b){
    return a + b;
}

PYBIND11_MODULE(example, m){
    m.doc() = "pybind11 example plugin";
    m.def("add", &add, "A function which adds two numbers");
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project(test)
set(pybind11_DIR /home/exinova/anaconda3/lib/python3.7/site-packages/pybind11/share/cmake/pybind11)
find_package(pybind11 REQUIRED)
if(${pybind11_FOUND})
message("pybind11 FOUND")
endif()
include_directories(${pybind11_INCLUDE_DIR})

pybind11_add_module(example example.cpp)
target_compile_definitions(example
                           PRIVATE VERSION_INFO=${EXAMPLE_VERSION_INFO})

a.py

import example
c = example.add(1, 2)
print(c)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值