[C++-sig] Passing C++ instance to embedded py
David Abrahams
dave at boostpro.com
Sun Dec 14 20:47:26 CET 2008
on Thu Nov 20 2008, fileoffset <fileoffset-AT-gmail.com> wrote:
> To best explain my problem, here is some code:
>
> struct A
> {
> A()
> {
> mTest = 1;
>
> std::cout << "Test: " << mTest;
>
> Py_Initialize();
> object main_module = import("__main__");
> object main_namespace = main_module.attr("__dict__");
>
> main_namespace["A_Instance"] = this;
>
> object result = exec_file(str("test.py"), main_namespace,
> main_namespace);
>
> std::cout << "Test: " << mTest;
> }
>
> int mTest;
> }
>
> in main.cpp or similar:
>
> BOOST_PYTHON_MODULE(MyModule)
> {
> class_<A>("A", init<>())
> .def_readwrite("Test", &A::mTest)
> ;
> }
>
> test.py:
>
> from MyModule import *
>
> A_Instance.Test = 5
>
>
> Essentially I want to be able to access and modify the properties of an instance of a
> C++ class
> at runtime.
>
> When I try code similar to above, python excepts, as I believe it
> attempts to copy-construct the A class instead of just pass the
> reference (this) so that i can modify it.
Correct.
>
> Is what I want possible? If not what would be a better way to do it?
main_module.attr("A_Instance") = ptr(this);
object d = main_module.attr("__dict__");
object result = exec_file(str("test.py"), d, d);
main_module.attr("A_Instance") = object(); // don't leave a dangling reference
(http://www.boost.org/doc/libs/1_37_0/libs/python/doc/v2/callbacks.html#argument_handling)
--
Dave Abrahams
BoostPro Computing
http://www.boostpro.com
More information about the Cplusplus-sig
mailing list