Created
December 6, 2018 08:51
-
-
Save rudeb0t/5b97c652a90511ee4852b9dfbe856829 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
c++ -O3 -Wall -shared -std=c++11 -fPIC `python -m pybind11 --includes` example.cpp -o _example`python-config --extension-suffix` |
This file contains hidden or 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 <string> | |
#include <sstream> | |
#include <pybind11/pybind11.h> | |
#include <pybind11/functional.h> | |
namespace py = pybind11; | |
typedef void (*cbfunc) (void*, const void*); | |
class Example { | |
private: | |
cbfunc m_cb; | |
public: | |
Example(); | |
int m_add(int i, int j); | |
void m_setCallback(cbfunc cb); | |
}; | |
Example::Example() { | |
m_cb = NULL; | |
} | |
int Example::m_add(int i, int j) { | |
if (m_cb) { | |
std::ostringstream oss; | |
oss << "Adding " << i << " and " << j; | |
m_cb(NULL, static_cast<const void*>(oss.str().c_str())); | |
} | |
return i + j; | |
} | |
void Example::m_setCallback(cbfunc cb) { | |
m_cb = cb; | |
} | |
static std::function<void(char *, const char *)> example_cb; | |
PYBIND11_MODULE(_example, m) { | |
m.doc() = "This is an example plugin\n" | |
"\n" | |
"Yey!"; | |
py::class_<Example>(m, "Example") | |
.def(py::init<>()) | |
.def("add", &Example::m_add) | |
.def("set_callback", [](Example &self, std::function<void(char*, const char*)> cb) { | |
example_cb = cb; | |
self.m_setCallback(+[](void* a, const void* b) { | |
example_cb(static_cast<char*>(a), static_cast<const char*>(b)); | |
}); | |
}); | |
} |
This file contains hidden or 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
import _example | |
def cb(*args): | |
print(args) | |
class A: | |
def __init__(self): | |
self.ex = _example.Example() | |
self.ex.set_callback(cb) | |
def foo(self): | |
print(self.ex.add(1, 2)) | |
a = A() | |
a.foo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment