一个pybind11的例子

首先在当前文件夹下安装pybind11。

然后编写以下3个文件:

1、CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

project(example LANGUAGES CXX)

add_subdirectory(pybind11)

pybind11_add_module(bar bar.cpp)

  

2、foo.py

import bar

hello_world = bar.HelloWorld()
hello_world.show("Hello world!")

  

3、bar.cpp

#include <iostream>

#include <pybind11/pybind11.h>

class HelloWorld {
public:
  void show(const std::string &s) { std::cout << s << std::endl; }
};

namespace py = pybind11;
PYBIND11_MODULE(bar, m) {
  py::class_<HelloWorld>(m, "HelloWorld")
      .def(py::init())
      .def("show", &HelloWorld::show);
}

  

最后编译运行。

posted @ 2024-05-07 17:17  南乡水  阅读(8)  评论(0编辑  收藏  举报