[C++-sig] Embedding...
Stefan Seefeld
seefeld at sympatico.ca
Wed Oct 25 19:46:01 CEST 2006
Beau Sapach wrote:
> Hello everyone,
>
> Thanks Stefan for your help! I know I'm posting a lot to this list, but I
> must admit I'm having a hard time wrapping my head around boost.python.
>
> If I want to make an instance of an object in C++ available to a python
> interpreter within the same .exe I must first expose the class correct?
> Using the same method described in the tutorial?
Right.
> Once that's done could I expose a global function (again within the same
> exe) that would return a pointer to an instance of the previously exposed
> class? Or is there an easier way of simply passing this to python?
Assuming you have set up a module 'world', containing a class 'hello'
(exported via the aforementioned class_<> harness), you can instantiate
an object of that type as:
----C++ code----
namespace bpl = boost::python;
bpl::object main = python::import("__main__");
bpl::object global(main.attr("__dict__"));
// Load the 'hello' module.
bpl::object result = bpl::exec("import hello\n", global, global);
// Get hold of the hello.world class.
bpl::object hello_class = global["hello.world"];
// Instantiate it.
bpl::object hello_instance = hello_class();
// Inject it into environment.
global['hello_instance'] = hello_instance;
// And run a script with it.
result = bpl::exec_file(script_name, global, global);
// Recover things from environment.
bpl::object greeting = global["greeting"];
----------------
The script itself can now assume the existence of 'hello_instance',
which was placed into the environment just before the script was
invoked with it (see above):
----python code----
# let's assume the 'hello.world' class exposes a 'greet' method.
greeting = hello_instance.greet()
-------------------
'greeting' becomes a new variable in the environment, which can
be extracted after the script's execution has finished. (See above.)
As you can see, the main device to exchange data between the C++ runtime
and the environment seen by the script is the 'global' dictionary that
gets passed to the exec / exec_file calls. It works two-ways.
HTH,
Stefan
--
...ich hab' noch einen Koffer in Berlin...
More information about the Cplusplus-sig
mailing list