views:

210

answers:

4

I'm researching how to best extend a C++ application with scripting capability, and I am looking at either Python or JavaScript. User-defined scripts will need the ability to access the application's data model.

Have any of you had experiences with embedding these scripting engines? What are some potential pitfalls?

+4  A: 

It's sure easy to embed Python by using the Boost::Python library (ok, ok, sarcasm.) Nothing is "easy" when it comes to cross-language functionality. Boost has done a great deal to aid such development. One of the developers I've worked with swears on the Boost->Python interface. His code can be programmed by a user in Python, with a REPL built right into the UI. Amazing.

However, my experience has been better observed using SWIG and other languages such as Java. I'm currently working with SWIG to wrap C++ with Python. There's all sorts of gotchas with exceptions, threading, cross-language polymorphism and the like.

I'd look at these two places first. As I said, nothing will be "easy" but both these make life more livable.

wheaties
A: 

Boost::Python, as in wheaties answer, is a very mature solution.

Lua has a reputation for being easy to embed but I have not tried this myself.

As a user of R, I am more interested in embedding R which is possible using the RInside package. A simple example is

#include <RInside.h>                // for the embedded R via RInside

int main(int argc, char *argv[]) {

    RInside R(argc, argv);          // create an embedded R instance 

    R["txt"] = "Hello, world!\n";   // assign a char* (string) to 'txt'

    R.parseEvalQ("cat(txt)");       // eval the init string, ignoring any returns

    exit(0);
}

and there are a couple more examples in the package. RInside essentially provides you a nice wrapper around the R engine using some of the Rcpp interface package.

Dirk Eddelbuettel
+7  A: 

Lua is also a great candidate for embedding in programs. Its very self contained, and even the native cross-language call system isn't bad.

For JavaScript, your best bet right now is to look at V8 (from Google), which is easy enough to work with.

Yann Ramin
You can use Lua easily in C++ with Luabind. Works well.
Nikko
+4  A: 

Unless you're really set on Python or Javascript, I'd give some consideration to using Lua. Since it's designed entirely as an embedded scripting engine, it eliminates quite a bit of overlap with what C and C++ already do well. It's also pretty easy to embed as long as you only interface between your code and the Lua engine in terms of C callable functions.

If you want to use a C++ level interface, you might want to take a look at LuaBind, which allows things like a Lua class deriving from (the proxy it generates for) a C++ class you wrote.

Jerry Coffin