Skip to content

Instantly share code, notes, and snippets.

@paulgessinger
Last active June 9, 2021 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulgessinger/f59e52ad6c6ac03e10a3999f40858851 to your computer and use it in GitHub Desktop.
Save paulgessinger/f59e52ad6c6ac03e10a3999f40858851 to your computer and use it in GitHub Desktop.
Assign C++ type to `std::function` with pybind11 without going through python
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <functional>
namespace py = pybind11;
struct Outer {
std::function<double(int, int)> func{nullptr};
};
struct Callable {
double operator()(int a, int b) { return a + b; }
};
PYBIND11_MODULE(demo, m) {
py::class_<Outer>(m, "Outer")
.def(py::init<>())
.def_readwrite("func", &Outer::func);
auto c = py::class_<Callable>(m, "Callable")
.def(py::init<>());
// adding this line fixes the python error, but the call now goes through python
// c.def("__call__", &Callable::operator());
}
project(pybind_repro)
cmake_minimum_required(VERSION 3.14)
find_package(pybind11 CONFIG REQUIRED)
pybind11_add_module(demo binding.cpp)
int main() {
Outer outer;
Callable callable;
outer.func = callable; // no problem
}
#!/usr/bin/env python3
import demo
outer = demo.Outer()
callable = demo.Callable()
outer.func = callable
# ^ this gives the following error
"""
Traceback (most recent call last):
File "test.py", line 7, in <module>
outer.func = callable
TypeError: (): incompatible function arguments. The following argument types are supported:
1. (self: demo.Outer, arg0: Callable[[int, int], float]) -> None
Invoked with: <demo.Outer object at 0x7fc275a716f0>, <demo.Callable object at 0x7fc275a71770>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment