Skip to content

Instantly share code, notes, and snippets.

@sizmailov
Last active October 4, 2019 12:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sizmailov/987dfdd2874514414317262b061f2890 to your computer and use it in GitHub Desktop.
Save sizmailov/987dfdd2874514414317262b061f2890 to your computer and use it in GitHub Desktop.
Module dependency in pybind11
#pragma once
struct Foo {
};
cmake_minimum_required(VERSION 3.14)
project(test_1)
set(CMAKE_CXX_STANDARD 14)
add_subdirectory(external/pybind11)
pybind11_add_module(pyinterfaceBase pyinterfaceBase.cpp)
pybind11_add_module(pyinterfaceDependent pyinterfaceDependent.cpp)
#include <pybind11/pybind11.h>
#include "Base.h"
namespace py = pybind11;
const char * f(Foo &foo) { return "Base::f(Foo& foo)"; }
PYBIND11_MODULE(pyinterfaceBase, m) {
py::class_<Foo>(m, "Foo")
.def(py::init<>());
m.def("f", f);
}
#include <pybind11/pybind11.h>
#include "Base.h"
namespace py = pybind11;
const char *g(Foo &foo) { return "Dependent::g(Foo& foo)"; }
PYBIND11_MODULE(pyinterfaceDependent, m) {
// next line is equivalent to python `import pyinterfaceBase; del pyinterfaceBase;`
py::module base = py::module::import("pyinterfaceBase");
// next line is equivalent to `from pyinterfaceBase import Foo as Goo`
m.attr("Goo") = base.attr("Foo");
m.def("g", g);
}
import pyinterfaceDependent as m
from pyinterfaceDependent import Goo
print(m.g(Goo()))
help(m)
################################
# Output:
################################
#Dependent::g(Foo& foo)
#Help on module pyinterfaceDependent:
#
#NAME
# pyinterfaceDependent
#
#FUNCTIONS
# g(...) method of builtins.PyCapsule instance
# g(arg0: pyinterfaceBase.Foo) -> str
#
#FILE
# /home/sergei/CLionProjects/test_1/cmake-build-debug/pyinterfaceDependent.cpython-36m-x86_64-linux-gnu.so#
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment