oh ..but I can compile above successfully and run the program
Just I need to call Python code now, do I need the SDK still?
Main Topics
Browse All TopicsHELLO
I would like to run a C++ program that can call a python code which is stored as a *.py. so that if I make any changes inside *.py, my C++ program can get the results.
In my code, I have a class CppClass and an object created from this class called cpp.
How can I pass this object to a *.py file and get the new results?
class CppClass {
public:
int getNum() {
return 8;
}
// int getNum2(){//
//return 12;
//}
};
#include "boost/python.hpp"
using namespace boost::python;
int main( int argc, char ** argv ) {
try {
Py_Initialize();
object main_module((
handle<>(borrowed(PyImport
object main_namespace = main_module.attr("__dict__
// main_namespace["cpp"] = ptr(&cpp);
main_namespace["CppClass"]
.def("getNum",&CppClass::g
CppClass cpp;
cpp.getNum();
main_namespace["multiply"]
handle<> ignored(( PyRun_String( "print multiply.getNum() \n",
Py_file_input,
main_namespace.ptr(),
main_namespace.ptr() ) ));
} catch( error_already_set ) {
PyErr_Print();
}
}
multiply.py
def multiply(a,b):
global c
print "Will compute", a, "times", b
c=c+(a*b)
return c
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
the topic you're tackling here is quite a very difficult one, since it is not limited to just execute some python code, but to pass objects forth and back. Of course this is possible, but not without quite a lot of work, because you need some sort of conversion tool - that translates c++ objects into python objects and back again.
To ease all that trouble, SWIG http://www.swig.org/ has been developed. It's quite a nifty tool, but still not so easy to handle especially when you want to implement something not so ordinary.
If you really need to call that python code I'd rather suggest to use Swig instead of other perhaps direct ways to interface to pyhton libs, because it's most likely to be better upgradeable. But when the complexity you there, is too much for you I'd rather suggest staying away from calling that python code and stick to rewriting it in c++.
I would like to allow user to change the script inside Python and the changed value will be run in C++.
So C++ calls Python code to do something and the user can write their own script inside Python and the results will be returned to C++.
Just like the game engine has scripting function. For example, in Second Lfe, we can write our own script using LSL
int main( int argc, char ** argv ) {
try {
Py_Initialize();
object main_module((
handle<>(borrowed(PyImport
object main_namespace = main_module.attr("__dict__
exec_file("multiply.py",
main_namespace.ptr(),
main_namespace.ptr() );
int a = extract<int>(main_namespac
int b = extract<int>(main_namespac
printf("%d * %d = %d\n", a,b,a*b );
} catch( error_already_set ) {
PyErr_Print();
}
}
multiply.py
a=5
b=12
thanks for your comment. Can I accept this questions and post a new one? and you try to help me? I am new in Python and I would like to do a game like application that allow user to write a script.
So I hope to use C++, Create a class / objects and pass to Python to do something. Then the object and the change stuff will return back to C++. Pass object is the main concept that I want to see how it works In web, I found similar things but I don't know how to make use of it with the .py file
Hope you can help
//////////////////////////
// Copyright David Abrahams 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICEN
// Example by Vladimir Prus that passes C++ object into Python, and
// call that object back from Python. Based on:
// embedded_hello -- A simple Boost.Python embedding example -- by
// Dirk Gerrits
#include <boost/python.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <stdexcept>
#include <cassert>
using namespace boost::python;
namespace python = boost::python;
void export_classes_to_python()
class B
{
public:
void say() const
{
std::cout << "B::say()\n";
}
};
class InterfaceForPython
{
public:
void say() const
{
std::cout << "InterfaceForPython::say()
}
void run() const
{
std::cout << "InterfaceForPython::run()
std::cout << "About to call Python function\n";
export_classes_to_python()
Py_Initialize();
// Retrieve the main module
object main_module((
handle<>(python::borrowed(
// Retrieve the main module's namespace
object main_namespace((main_modul
B* b = new B;
// If called here, we get exception in executing PyRun_String
main_namespace["context"] = ptr(b);
// Prepare the Python code. We'll call the 'foo' method.
python::handle<> result(
PyRun_String(
"from embedded_hello import *\n"
"def foo(p): print 'Calling C++ method from Python'; p.say(); context.say()\n"
"",
Py_file_input, main_namespace.ptr(), main_namespace.ptr())
);
// Result is not needed
result.reset();
// Works fine here
// main_namespace["context"] = ptr(b);
// Get the 'foo' function.
object foo(main_module.attr("foo"
// Invoke it, passing ourselfs *by pointer*.
foo(ptr(this));
}
};
BOOST_PYTHON_MODULE(embedd
{
class_<InterfaceForPython>
.def("say", &InterfaceForPython::say);
class_<B>("B")
.def("say", &B::say);
}
void export_classes_to_python()
{
// Register the module with the interpreter
if (PyImport_AppendInittab("e
throw std::runtime_error("Failed
"builtin modules");
}
int main()
{
InterfaceForPython pyint;
if (python::handle_exception(
{
if (PyErr_Occurred())
PyErr_Print();
return 1;
}
return 0;
}
You create Python extension (say mygame) for say GameEngine() class and call it from Python.
You debug it from Python command-line without embedding like that:
> python
>>> import mygame
>>> e = mygame.GameEngine()
>>> print e.objects()
>>> print e.characters()
>>> e.charecters(0).move(10,20
When it works, you embed your script (like above) in your C++ program like it was discussed in that question.
Business Accounts
Answer for Membership
by: DeepuAbrahamKPosted on 2007-08-20 at 02:38:19ID: 19729063
Yes you can have embedded python scripting in c++.You need to have Phython SDK which will have the include files as well as certain lib files.For more details visit www.python.org
Best Regards,
DeepuAbrahamK