Last active
June 9, 2021 18:45
-
-
Save paulgessinger/f59e52ad6c6ac03e10a3999f40858851 to your computer and use it in GitHub Desktop.
Assign C++ type to `std::function` with pybind11 without going through python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
project(pybind_repro) | |
cmake_minimum_required(VERSION 3.14) | |
find_package(pybind11 CONFIG REQUIRED) | |
pybind11_add_module(demo binding.cpp) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main() { | |
Outer outer; | |
Callable callable; | |
outer.func = callable; // no problem | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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