Created
November 19, 2009 23:04
-
-
Save mashiro/239128 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
#define BOOST_PYTHON_STATIC_LIB | |
#include <boost/python.hpp> | |
#include <boost/ref.hpp> | |
#include <iostream> | |
namespace py = boost::python; | |
class IntValue | |
{ | |
public: | |
IntValue() {} | |
IntValue(int value) : value_(value) {} | |
int get() const { return value_; } | |
void set(int value) { value_ = value; } | |
static void py_export() | |
{ | |
py::class_<IntValue>("IntValue") | |
.def("get", &IntValue::get) | |
.def("set", &IntValue::set) | |
.add_property("value", &IntValue::get, &IntValue::set) | |
; | |
} | |
private: | |
int value_; | |
}; | |
BOOST_PYTHON_MODULE(foo) | |
{ | |
IntValue::py_export(); | |
} | |
void test() | |
{ | |
try | |
{ | |
py::object main_module = py::import("__main__"); | |
py::object main_namespace = main_module.attr("__dict__"); | |
int a = 1; | |
IntValue b(2); | |
IntValue c(3); | |
IntValue* d = new IntValue(4); | |
IntValue* e = new IntValue(5); | |
py::exec("import foo", main_namespace); | |
main_namespace["a"] = a; | |
main_namespace["b"] = b; | |
main_namespace["c"] = boost::ref(c); | |
main_namespace["d"] = d; | |
main_namespace["e"] = boost::ref(*e); | |
py::exec( | |
"a *= 10\n" | |
"b.value *= 10\n" | |
"c.value *= 10\n" | |
"d.value *= 10\n" | |
"e.value *= 10\n" | |
, main_namespace); | |
std::cout << a << std::endl; // 1 | |
std::cout << b.get() << std::endl; // 2 | |
std::cout << c.get() << std::endl; // 30 | |
std::cout << d->get() << std::endl; // 4 | |
std::cout << e->get() << std::endl; // 50 | |
delete d; | |
delete e; | |
} | |
catch (const py::error_already_set&) | |
{ | |
PyErr_Print(); | |
} | |
} | |
int main(int argc, char** argv) | |
{ | |
PyImport_AppendInittab("foo", initfoo); | |
Py_Initialize(); | |
test(); | |
Py_Finalize(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment