Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating a script language into a C++ application [closed]

I'm really new to C++ and I've come across a problem I've not been able to solve by reading documentations.

I want to embed a script language into my c++ application. That language could be javascript, lua or preferably python.

I'm not looking for something like Boost.Python / swig, something that is able to wrap my c++ functions / classes to a python interface, but rather a python_evaluate_and_return_result_as_variable("my_code"); function.

I have a whole bunch of structs containing a few integers:

struct my_integers {
    int a;
    int b;
    int c;
    int d;
    int e;
};

Now I want to do some math with these integers, for example:

i.a = i.c * i.e;

The math I want to do will be changing a lot in the future and I need people other then me be able to change the math without having access to the c++ code.

I'm thinking about a code structure like this:

  1. I initialize my struct and fill it with the starting values
  2. I load an external python function, lets say "my_python_function", that takes the struct as an argument and does so math with it before returning it.
  3. I get my struct like i = my_python_function_cppwrapper(i)

Is something like that possible? I googled a lot for this but the only thing I seem to find are wrappers that provide c++ -> python (or the other way around) functionallity without really interacting with variables.

I'd be really thankful for any help,
Robin.

like image 666
Robin Avatar asked Sep 23 '10 16:09

Robin


4 Answers

Why not use Boost.Python? You can expose your data classes to Python and execute a script/function as described here.

like image 117
David Feurle Avatar answered Oct 04 '22 17:10

David Feurle


The Python documentation has a page on embedding Python in a C or C++ application.

like image 36
Jon Purdy Avatar answered Oct 04 '22 16:10

Jon Purdy


If you want to simply run Python scripts from C/C++, then use the Python C API. In your C/C++ code:

PyRun_SimpleString("import math; x = math.sqrt(2 * 2)");

For more complicated things, you will have to look at the API docs, but it's pretty straightforward.

like image 31
Ross Light Avatar answered Oct 04 '22 17:10

Ross Light


How about embedding a JavaScript engine, such as V8?

like image 20
Matthijs Bierman Avatar answered Oct 04 '22 15:10

Matthijs Bierman