[C++-sig] Executing python code from C++
Murray Cumming
murrayc at murrayc.com
Sun Feb 7 22:51:45 CET 2010
On Sun, 2010-02-07 at 09:51 -0500, Stefan Seefeld wrote:
>
> Sorry, I don't understand the question. Can you give an example of
> what
> you want to do ? May be you want to "exec" some python code that
> defines
> a function, which you then want to extract and call later ?
> That may look like this:
>
> // Retrieve the main module
> bpl::object main = bpl::import("__main__");
> // Retrieve the main module's namespace
> bpl::object global(main.attr("__dict__"));
> // Define the 'embedded' Python code...
> std::string py_code = "def greeting(): print 'hello world !'";
> // ...and execute it.
> bpl::object result = bpl::exec(py_code, global, global);
> // Extract the function
> bpl::object greeting = global["greeting"];
Yes, this last line is what I figured out from some other example code.
It does work for me. Thanks.
I guess it make sense in terms of the weird Python C API, but it's all
far from obvious without knowledge of that.
Thanks again.
--
murrayc at murrayc.com
www.murrayc.com
www.openismus.com
More information about the Cplusplus-sig
mailing list