On 01/09/2010 01:52 PM, devin kelly wrote:
Hello,

I'm trying to expose some data that I develop in C++ to python. Basically, the reverse of this sample code:

#include <iostream>
#include <python2.6/Python.h>
#include <boost/python.hpp>
#include <boost/python/exec.hpp>

int main(){

        Py_Initialize();
        object main_module = import("__main__");
        object main_namespace = main_module.attr("__dict__");
        ignored = exec("result = 5 ** 2", main_namespace);
        int five_squared = extract<int>(main_namespace["result"]);
        std::cout << five_squared << std::endl;

        return 0;
}


So this code starts the python interpreter, squares 5 (in python) and then extracts the result to an int called five_squared. This works fine for me, it's basically an example straight out of the boost.python webpage.

What I'd really like to do though is have an int that I initialize in C++ and then square in python. So this would require me to pass (or expose) that data to python. I've been trying this for a while and have had no luck whatsoever. The best I can think of is code like this:

int main(){
        Py_Initialize();
        object main_module = import("__main__");
        object main_namespace = main_module.attr("__dict__");
        main_namespace["num2square"] = 6;
        ignored = exec("result = num2square ** 2", main_namespace);
        int five_squared = extract<int>(main_namespace["result"]);
        std::cout << five_squared << std::endl;
        return 0;
}

This doesn't work.  Python throws an error.  What am I doing wrong??

It might help indicating what error Python actually throws.

Also, if all you want is to evaluate an expression, I'd suggest you use "eval()", not "exec()".

        Stefan

--

      ...ich hab' noch einen Koffer in Berlin...

_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to