[C++-sig] how t o specify and/or update global dictionary for bp::call call
Stefan Seefeld
seefeld at sympatico.ca
Thu Sep 4 15:00:54 CEST 2008
Gennadiy Rozental wrote:
> Hi,
>
> I've got class implemented in python, inherited from C++ class. I am using
> wrapper/get_overload to invoke it's methods:
>
> bp::override o = this->get_override( "update" );
> bp::call< void >( o.ptr(), arg1, arg2 );
>
> Now in update method I need to refer to the function foo that reside
> in module moo.
>
> I've tried to add
> from moo import foo
> and
> from moo import *
>
> before class definition:
>
> class MyPyDerivedClass( MyCPPBase ):
> def update( s, arg1, ARG2 ):
> foo()
>
> Both attempts were futile. Looks like global dictionary during update call does
> not contain foo.
>
For avoidance of doubt: you are saying the import itself was successful,
but there was no 'foo' symbol in the global namespace after that point ?
I just modified the exec.cpp test (libs/python/tests/exec.cpp), and it
all works like a charm.
(For reference: go to libs/python/tests/exec.cpp and modify the
'exec_test' function to simulate what you want. Here is the modified
script I use:
python::object main = python::import("__main__");
python::object global(main.attr("__dict__"));
python::object result = python::exec(
"from embedded_hello import * \n"
"from sys import * \n"
//<-- added just to show how to populate the global namespace of the script
"class PythonDerived(Base): \n"
" def hello(self): \n"
" print platform \n"
//<-- use it
" return 'Hello from Python!' \n",
global, global);
python::object PythonDerived = global["PythonDerived"];
python::object py_base = PythonDerived();
Base& py = python::extract<Base&>(py_base);
assert(py.hello() == "Hello from Python!");
> P.S. solution to add import method inside update method is unacceptable for
> various (mostly political) reasons, though it obviously will work. I definitely
> need this outside class definition
>
> P.P.S. Instance of class MyPyDerivedClass is created on C++ side based on
> pre-cached python type:
>
> cpp_derived = m_py_type();
>
Sounds like what you are doing is very similar to what the test I just
exerimented with does. Right ?
HTH,
Stefan
--
...ich hab' noch einen Koffer in Berlin...
More information about the Cplusplus-sig
mailing list