- You should have the
CMakeFiles.txt
and thesrc
folder to start.
The CMakeFiles.txt:
cmake_minimum_required(VERSION 3.4...3.18)
project(pimymath)
add_library(mymath STATIC src/mymath.cpp)
set_target_properties(mymath PROPERTIES POSITION_INDEPENDENT_CODE ON)
add_subdirectory(pybind11)
pybind11_add_module(pimymath src/binder.cpp)
target_link_libraries(pimymath PRIVATE mymath)
In src
, you have 3 files:
mymath.h
mymath.cpp
binder.cpp
// mathmath.h
#pragma once
int add(int i, int j) ;
// mathmath.cpp
#include "mymath.h"
int add(int i, int j) {
return i + j;
}
// binder.cpp
#include <pybind11/pybind11.h>
#include "mymath.h"
#define STRINGIFY(x) #x
#define MACRO_STRINGIFY(x) STRINGIFY(x)
namespace py = pybind11;
PYBIND11_MODULE(pimymath, m) {
m.doc() = R"pbdoc(
Pybind11 example plugin
-----------------------
.. currentmodule:: pimymath
.. autosummary::
:toctree: _generate
add
subtract
)pbdoc";
m.def("add", &add, R"pbdoc(
Add two numbers
Some other explanation about the add function.
)pbdoc");
m.def("subtract", [](int i, int j) { return i - j; }, R"pbdoc(
Subtract two numbers
Some other explanation about the subtract function.
)pbdoc");
#ifdef VERSION_INFO
m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO);
#else
m.attr("__version__") = "dev";
#endif
}
- Install
pybind11
git clone https://github.com/pybind/pybind11.git
- Install Python virtualenv (see this link )
pip3 install virtualenv
- Create a virtual env
python3 -m venv project_env
- Activate the above set project_env virtual envirnonment
source project_env/bin/activate
- Create a folder
build
and go inside
mkdir build && cd build
- Type
cmake ..
- Compile your dynamic lib:
make mymath
- Then, the Python wrapping
make pimymath
- Test your project
>>> import pimymath
>>> pimymath.add(1,2)
3
>>> pimymath.subtract(1,2)
-1
>>> quit()