Skip to content

Instantly share code, notes, and snippets.

@rudeb0t
Created December 6, 2018 08:51
Show Gist options
  • Save rudeb0t/5b97c652a90511ee4852b9dfbe856829 to your computer and use it in GitHub Desktop.
Save rudeb0t/5b97c652a90511ee4852b9dfbe856829 to your computer and use it in GitHub Desktop.
c++ -O3 -Wall -shared -std=c++11 -fPIC `python -m pybind11 --includes` example.cpp -o _example`python-config --extension-suffix`
#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));
});
});
}
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