[C++-sig] Exposing C++ data with Boost.Python
devin kelly
dwwkelly at gmail.com
Sat Jan 9 19:52:48 CET 2010
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??
Thanks for any help,
Devin
--
http://users.wpi.edu/~dkelly/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20100109/1e9a4118/attachment.htm>
More information about the Cplusplus-sig
mailing list