Skip to content

Instantly share code, notes, and snippets.

@xaliphostes
Created January 10, 2023 07:43
Show Gist options
  • Save xaliphostes/70416d49ffc115f66f577bb1909eb0ac to your computer and use it in GitHub Desktop.
Save xaliphostes/70416d49ffc115f66f577bb1909eb0ac to your computer and use it in GitHub Desktop.
pybind11 simple test

Wrapping C++ for Python

Your project

  1. You should have the CMakeFiles.txt and the src 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 and Python env

  1. Install pybind11
git clone https://github.com/pybind/pybind11.git
  1. Install Python virtualenv (see this link )
pip3 install virtualenv
  1. Create a virtual env
python3 -m venv project_env
  1. Activate the above set project_env virtual envirnonment
source project_env/bin/activate

Compile your pybind11 project

  1. Create a folder build and go inside
mkdir build && cd build
  1. Type
cmake ..
  1. Compile your dynamic lib:
make mymath
  1. Then, the Python wrapping
make pimymath
  1. Test your project
>>> import pimymath
>>> pimymath.add(1,2)
3
>>> pimymath.subtract(1,2)
-1
>>> quit()

References

  1. This video
  2. This article
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment