Implementing scripts in c++ app - c++

I want to move various parts of my app into simple scripts, to allow people that do not have a strong knowledge of c++ to be able to edit and implement various features.
Because it's a real time app, I need to have some kind of multitasking for these scripts. Ideally I want it so that the c++ app calls a script function which then continues running (under the c++ thread) until either a pause point (Wait(x)), or it returns. In the case of it waiting the state needs to be saved ready for the script to be restarted the next time the app loops after the duration has expired.
The scripts also need to be able to call c++ class methods, ideally using the c++ classes rather than plain wrapper functions around c++ classes.
I don't want to spend a massive amount of time implementing this, so using an existing scripting language is preferred to writing my own. I heard that Python and Lua can be integrated into a c++ app, but I do not know how to do this to achieve my goals.
The scripts must be able to call c++ functions
The scripts must be able to "pause" when certain functions are called (eg. Wait), and be restarted again by the c++ thread
Needs to be fast -- this is for a real time app and there could potentially be a lot of scripts running.
I can probably roll the multitasking code fairly easily, provided the scripts can be saved and restarted (possibly by a different thread to the original).

You can use either Lua or Python. Lua is more "lightweight" than python. It's got a smaller memory footprint than python does and in our experience was easier to integrate (people's mileage on this point might vary). It can support a bunch of scripts running simultaneously. Lua, at least, supports stopping/starting threads in the manner you desire.
Boost.python is nice, but in my (limited) experience, it was difficult for us to get compiling for our different environments and was pretty heavyweight. It has (in my opinion) the disadvantage of requiring Boost. For some, that might not be a problem, but if you don't need Boost (or are not using it), you are introducing a ton of code to get Boost.python working. YMMV.
We have built Lua into apps on multiple platforms (win32, Xbox360 and PS3). I believe that it will work on x64. The suggestion to use Luabind is good. We wound up writing our own interface between the two and while not too complicated, having that glue code will save you a lot of time and perhaps aggravation.
With either solution though, debugging can be a pain. We currently have no good solution for debugging Lua scripts that are embedded into our app. Since we haven't used python in our apps I can't speak to what tools might be available there, but a couple of years ago the landscape was roughly the same -- poor debugging. Having scripting to extend functionality is nice, but bugs in the scripts can cause problems and might be difficult to locate.
The Lua code itself is kind of messy to work with if you need to make changes there. We have seen bugs in the Lua codebase itself that were hard to track down. I suspect that Boost::Python might have similar problems.
And with any scripting language, it's not necessarily a solution for "non-programmers" to extend functionality. It might seem like it, but you will likely wind up spending a fair amount of time either debugging scripts or even perhaps Lua.
That all said, we've been very happy with Lua and have shipped it in two games. We currently have no plans to move away from the language. All in all, we've found it better than other alternatives that were available a couple of years ago. Python (and IronPython) are other choices, but based on experience, they seem more heavy handed than Lua. I'd love to hear about other experiences there though.

I can highly recommend that you take a look at Luabind. It makes it very simple to integrate Lua in your C++ code and vice versa. It is also possible to expose whole C++ classes to be used in Lua.

Your best bet is to embed either lua (www.lua.org) or python (www.python.org). Both are used in the game industry and both access extern "C" functions relatively easily with lua having an edge here (because data types are easier to translate between lua and C). Interfacing to C++ objects will be a bit more work on your end, but you can look up how to do this on Google, or on lua or python discussion forums.
I hope that helps!

You can definitely do what you want with Python. Here are the docs on embedding Python into an application. I'm pretty sure Lua would work too, I'm just less familiar with it.
You're describing cooperative multi-tasking, where the script needs to call a Break or Wait function periodically. Perhaps a better solution would be to run the scripting language in its own thread, and then use mutexes or lock-free queues for the interfaces between the scripting language and the rest of your program. That way a buggy script that doesn't call Break() often enough can't accidentally freeze your program.

Take a look at the Boost.Python library. It looks like it should be fairly straightforward to do what you want.

Take a look at SWIG. I've used it to interface with Python, but it supports many other languages.

One more vote for Lua. It's small, it's fast, it doesnt consume much memory (for games your best bet is to allocate big buffer at the initialization and re-direct all Lua memory allocations there). We used tolua to generate bindings, but there are other options, most of them much smaller/easier to use (IMO) than boost.python.

As for debugging Lua (if you go that route), I have been using DeCoda, and it has not been bad. It pretends to be an IDE, but sorta fails at that, but you can attach The debugging process to visual studio, and go down the call stack at break points. Very handy for Tracking down that bug.

You can also embed C/C++ scripts using Ch. I've been using it for a game project I'm working on, and it does well. Nice blend of power and adaptability.

Related

How interoperability works

I know that many large-scale applications such as video games are created using multiple langages. For example, it's likely the game/physics engines are written in C++ while gameplay tasks, GUI are written in something like Python or Lua.
I understand why this division of roles is done; use lower-level languages for tasks that require extreme optimization, tweaking, efficiency and speed, while using higher-level languages to speed up production time, reduce nasty bugs ect.
Recently, I've decided to undertake a larger personal project and would like to divy-up parts of the project similar to above. At this point in time, I'm really confused about how this interoperability between languages (especially compiled vs interpreted) works.
I'm quite familiar with the details of going from ANSCII code test to loading an executable, when written in something like C/C++. I'm very curious at how something like a video game, built from many different languages, works. This is a large/broad question, but specifically I'm interested in:
How does the code-level logic work? I.e. how can I call Python code from a C++ program? Especially since they don't support the same built-in types?
What does the program image look like? From what I can tell, a video game is running in a single process, so what does the runtime image look like when running a C/C++ program that calls a Python function?
If calling code from an interpreted language from a compiled program, what are the sequence of events that occur? I.e If I'm inside my compiled executable, and for some reason have a call to an interpreted language inside a loop, do I have to wait for the interpreter every iteration?
I'm actually finding a hard time finding information on what happening at the machine-level, so any help would be appreciated. Although I'm curious in general about interoperation of software, I'm specifically interested in C++ and Python interaction.
Thank you very much for any insight, even if it's just pointing me to where I can find more information.
In the specific case of python, you have basically three options (and this generally applies across the board):
Host python in C++: From the perspective of the C++ programme, the python interpreter is a C library. On the python side, you may or may not need to use something like ctypes to expose the C(++) api.
Python uses C++ code as DLLs/SOs - C++ code likely knows nothing of python, python definitely has to use a foreign function interface.
Interprocess communication - basically, two separate processes run, and they talk over a socket. These days you'd likely use some kind of web services architecture to accomplish this.
Depending on what you want to do:
Have a look at SWIG: http://www.swig.org/ It's a tool that aims to connect C/C++ code with Python, Tcl, Perl, Ruby, etc. The common use case is a Python interface (graphical or not) that will call the C/C++ code. SWIG will parse the C/C++ code in order to generate the interfaces.
Libpython: it's a lib that allows you to embed Python code. You have some examples here: http://docs.python.org/3.0/extending/embedding.html

Using scripting language in C++

My question is a little bit stupid but I decided to ask advanced programmers like some of you. So I want to make a "dynamic" C++ program. My idea is to compile it and after compilation (maybe with scripting language like python) to change some how the code of the program. I know you will tell me that after the compilation I can not change the code but is there a way of doing that. Thank you!
You could design a modular architecture using plugins in external libraries. For example you could use the Command Pattern. That way you can dynamically load code that was generated after you main program. You would have to fix an interface though. Functions like GetProcAddress in the Windows api might be a good point to start.
For dynamic coding and rapid prototyping I recommend to have a look at Lua. The engine is very small and easy to integrate in your c++ program.
The only way to do that in C++ is to unload the DLL with the code to be
modified, modify the sources, invoke the compiler to regenerate the DLL,
and reload the DLL. It's very, very heavy weight, and it only works if
the compiler is present on the machines where the code is to be run.
(Usually the case under Unix, rarely the case with Windows.)
Interpreted languages like Python are considerably more dynamic; Python
has a built-in function to execute a string as Python code, for example.
If you need dynamically modifiable code, I'd suggest embedding Python in
your application, and using it for the dynamic parts.
Personally I have never played with re-compiling C++ during runtime, and I do not intend too. However I have been doing a lot of embedding of scripting languages lately.
Someone else mentioned the obvious first choice for embedding: Lua. Lua is a pretty popular language to embed and you will find a bunch of documentation about how to do it. Integrating it into the C++ will allow you to define behavior at runtime like you want.
What I am using is a wonderful langauge called Squirrel. It is a lot like Lua but with native object(class) support and C++-like syntax. I have managed to embed it into a C++ application, and through using the sqrat binding library both languages can share information easily.
I have squirrel building and initializing my UI. As a result, 0 compiling is required in order to craft and structure my UI for my game. I intend to take this a step further and use this gameplay-side in order to create similar behavior you are looking for(changing behavior at runtime through dynamic code usage)
I recommend Checking out squirrel here: http://www.squirrel-lang.org/
I plan on writing tutorials on how to embed squirrel and install the binding library, but I have not started on them yet. If I can remember, I will edit this post in the future (could be a few months) once I have completed them. In the meantime give it a shot yourself. You may find it to your liking.

replace c++ with go + swig

I recently asked this question https://softwareengineering.stackexchange.com/questions/129076/go-instead-of-c-c-with-cgo and got some very interesting input. However there's a mistake in my question: I assumed cgo could also be used to access c++ code but that's not possible. Instead you need to use SWIG.
The go faq says "The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries. "
my question:
Is it possible to access high-level c++ frameworks such as QT with SWIG + Go and get productive? I'd like to use Go as a "scripting language" to utilize c++ libraries.
Have you any experience with go and swig? Are there pitfalls I have to be aware of?
Update/Answer: I've asked this over IRC too and I think the question is solved:
SWIG is a rather clean way of interfacing c++ code from other languages. Sadly matching the types of c++ to something like go can be very complex and in most cases you have to specify the mapping yourself. That means that SWIG is a good way to leverage an existing codebase to reuse already written algorithms. However mapping a library like Qt to go will take you ages. Mind it's surely possible but you don't want to do it.
Those of you that came here for gui programming with go might want try go-gtk or the go version of wxWidgets.
Is it possible? Yes.
Can it be done in a reasonably short period of time? No.
If you go back and look at other projects that have taken large frameworks and tried to put an abstraction layer on it, you'll find most are "incomplete". You can probably make a fairly good start and get some initial wrappers in place, but generally even the work to get the simple cases solved takes time when there is a lot of underlying code to wrap, even with automated tools (which help, but are never a complete solution). And then... you get to the nasty remaining 10% that will take you forever (ok, a really really long time at least). And then think about how it's a changing target in the first place. Qt, for example, is about to release the next major rewrite.
Generally, it's safest to stick to the framework language that the framework was designed for. Though many have language extensions within the project itself. For example, for Qt you should check out QML, which provides (among many other things) a javascript binding to Qt. Sort of. But it might meet your "scripting" requirement.
A relevant update on this issue: it is now possible to interact with C++ using cgo with this CL, which is merged for Go 1.2. It is limited, however, to C-like functions calls, and classes, methods and C++ goodies are not supported (yet, I hope).

Scripting language for C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm getting a little rusty in scripting languages, provided they're popping like mushrooms lately :)
Today I thought that it would be nice to have a scripting language that talks seamlessly to C++, that is, could use C++ classes, and, the most important for me, could be compiled into C++ or some DLL/.SO (plus its .h) so that I could link it into my C++ program and make use of the classes the script defines or implements.
I know I could embed any popular scripting language such as lua, ruby, python... but the interface usually includes some kind of "eval" function that evaluates the provided scripting code. Depending on the tool used to couple C++ and the scripting language, the integration for callbacks of the script into C++ could be more or less easy to write, but I haven't seen any scripting language that actually allows me to write independent modules that are exposed as a .h and .so/dll to my program (maybe along the lines of a scripting language that generates C++ code).
Do you know any such tool/scripting language?
Thanks in advance.
PD. I've been thinking along the lines of Vala or Haskell's GHC. They generate C, but not C++...
UPDATE 2020: Today I would probably go with Lua + Sol2/3 except if I really want to avoid Lua as a language. Chaiscript becomes a good candidate in this case though it is not optimal performance-wise compared to Lua+Sol2/3 (though it was greatly improved through years so it is still good enough in many cases).
Falcon have been dead for some years, RIP.
The following ones are more C++ integration oriented than language bindings :
ChaiScript - trying at the moment in a little project, interesting, this one is MADE with C++ in mind and works by just including a header! Not sure if it's good for a big project yet but will see, try it to have some taste!
(not maintained anymore) Falcon - trying on a big project, excellent; it's not a "one include embed" as ChaiScript but it's because it's really flexible, and totally thought to be used in C++ (only C++ code in libs) - I've decided to stick with it for my biggest project that require a lot of scripting flexibility (comparable to ruby/python )
AngelScript - didn't try yet
GameMonkey - didn't try yet
Io - didn't try yet
For you, if you really want to write your scripting module in C++ and easily expose it to the scripting language, I would recommand going with Falcon. It's totally MADE in C++, all the modules/libraries are written that way.
The question usually asked in this context is: how do I expose my C++ classes so they can be instantiated from script? And the answer is often something like http://www.swig.org/
You're asking the opposite question and it sounds like you're complicating matters a bit. A scripting engine that produced .h files and .so files wouldn't really be a scripting engine - it would be a compiler! In which case you could use C++.
Scripting engines don't work like that. You pass them a script and some callbacks that provide a set of functions that can be called from the script, and the engine interprets the script.
Try lua: http://www.lua.org/
For using C++ classes in lua you can use:
To generate binding use tolua++: http://www.codenix.com/~tolua/
It takes a cleaned up header as input and outputs a c file that does the hard work. Easy, nice and a pleasure to work with.
For using Lua objects in C++ I'd take the approach of writing a generic Proxy object with methods like (field, setField, callMethod, methods, fields).
If you want a dll you could have the .lua as a resource (in Windows, I don't know what could be a suitable equivalent for Linux) and on your DllMain initialize your proxy object with the lua code.
The c++ code can then use the proxy object to call the lua code, with maybe a few introspection methods in the proxy to make this task easier.
You could just reuse the proxy object for every lua library you want to write, just changing the lua code provided to it.
This is slightly outside my area of expertise, but I'm willing to risk the downvotes. :-)
Boost::Python seems to be what you're looking for. It uses a bit of macro magic to do its stuff, but it does expose Python classes to C++ rather cleanly.
I'm the author of LikeMagic, a C++ binding library for the Io language. (I am not the author of Io.)
http://github.com/dennisferron/LikeMagic
One of my explicit goals with LikeMagic is complete and total C++ interoperability, in both directions. LikeMagic will marshal native Io types as C++ types (including converting between STL containers and Io's native List type) and it will represent C++ classes, methods, fields, and arrays within Io. You can even pass a block of Io code out of the Io environment and use it in C++ as a functor!!
Wrapping C++ types up for consumption in Io script is simple, quick and easy. Accessing script objects from C++ does require an "eval" function like you described, but the template based type conversion and marshaling makes it easy to access the result of executing a script string. And there is the aforementioned ability to turn Io block() objects into C++ functors.
Right now the project is still in the early stages, although it is fully operational. I still need to do things like document its build steps and dependencies, and it can only be built with gcc 4.4.1+ (not Microsoft Visual C++) because it uses C++0x features not yet supported in MSVC. However, it does fully support Linux and Windows, and a Mac port is planned.
Now the bad news: Making the scripts produce .h files and .so or .dll files callable from C++ would not only require a compiler (of a sort) but it would also have to be a JIT compiler. That's because (in many scripting languages, but most especially in Io) an object's methods and fields are not known until runtime - and in Io, methods can even be added and removed from live objects! At first I was going to say that the very fact that you're asking for this makes me wonder if perhaps you don't really understand what a dynamic language is. But I do believe in a way of design in which you first try to imagine the ideal or easiest possible way of doing something, and then work backwards from there to what is actually possible. And so I'll admit from an ease-of-use standpoint, what you describe sounds easier to use.
But while it's ideal, and just barely possible (using a script language with JIT compilation), it isn't very practical, so I'm still unsure if what you're asking for is what you really want. If the .h and .so/.dll files are JITted from the script, and the script changes, you'd need to recompile your C++ program to take advantage of the change! Doesn't that violate the main benefit of using script in the first place?
The only way it is practical would be if the interfaces defined the scripts do not change, and you just are making C++ wrappers for script functions. You'd end up having a lot of C++ functions like:
int get_foo() { return script.eval("get_foo()"); }
int get_bar() { return script.eval("get_bar()"); }
I will admit that's cleaner looking code from the point of view of the callers of the wrapper function. But if that's what you want, why not just use reflection in the scripting language and generate a .h file off of the method lists stored in the script objects? This kind of reflection can be easily done in Io. At some point I plan to integrate the OpenC++ source-to-source translator as a callable library from LikeMagic, which means you could even use a robust C++ code generator instead of writing out strings.
You can do this with Lua, but if you have a lot of classes you'll want a tool like SWIG or toLua++ to generate some of the glue code for you.
None of these tools will handle the unusual part of your problem, which is to have a .h file behind which is hidden a scripting language, and to have your C++ code call scripts without knowing that that are scripts. To accomplish this, you will have to do the following:
Write the glue code yourself. (For Lua, this is relatively easy, until you get into classes, whereupon it's not so easy, which is why tools like SWIG and toLua++ exist.)
Hide behind the interface some kind of global state of the scripting interpreter.
Supposing you have multiple .h files that each are implemented using scripts, you have to decide which ones share state in the scripting language and which ones use separate scripting states. (What you basically have is a VM for the scripting language, and the extremes are (a) all .h files use the same VM in common and (b) each .h file has its own separate, isolated VM. Other choices are more complicated.)
If you decide to do this yourself, writing the glue code to turn Lua tables into C++ classes (so that Lua code looks like C++ to the rest of the program) is fairly straightforward. Going in the other direction, where you wrap your C++ in Lua (so that C++ objects look to the scripts like Lua values) is a big pain in the ass.
No matter what you do, you have some work ahead of you.
Google's V8 engine is written in C++, I expect you might be able to integrate it into a project. They talk about doing that in this article.
Good question, I have often thought about this myself, but alas there is no easy solution to this kind of thing. If you are on Windows (I guess not), then you could achieve something like this by creating COM components in C++ and VB (considering that as a scripting language). The talking happens through COM interfaces, which is a nice way to interop between disparate languages. Same holds for .NET based languages which can interop between themselves.
I too am eager to know if something like this exists for C++, preferably open source.
You might check into embedding Guile (a scheme interpreter) or V8 (Google's javascript interpreter - used in Chrome - which is written in C++).
Try the Ring programming language
http://ring-lang.net
(1) Extension using the C/C++ languages
https://en.wikibooks.org/wiki/Ring/Lessons/Extension_using_the_C/C%2B%2B_languages
(2) Embedding Ring Interpreter in C/C++ Programs
https://en.wikibooks.org/wiki/Ring/Lessons/Embedding_Ring_Interpreter_in_C/C%2B%2B_Programs
(3) Code Generator for wrapping C/C++ Libraries
https://en.wikibooks.org/wiki/Ring/Lessons/Code_Generator_for_wrapping_C/C%2B%2B_Libraries

What is a good scripting language to integrate into high-performance applications?

I'm a game's developer and am currently in the processing of writing a cross-platform, multi-threaded engine for our company. Arguably, one of the most powerful tools in a game engine is its scripting system, hence I'm on the hunt for a new scripting language to integrate into our engine (currently using a relatively basic in-house engine).
Key features for the desired scripting system (in order of importance) are:
Performance - MUST be fast to call & update scripts
Cross platform - Needs to be relatively easy to port to multiple platforms (don't mind a bit of work, but should only take a few days to port to each platform)
Offline compilation - Being able to pre-parse the script code offline is almost essential (helps with file sizes and load times)
Ability to integrate well with c++ - Should be able to support OO code within the language, and integrate this functionality with c++
Multi-threaded - not required, but desired. Would be best to be able to run separate instances of it on multiple threads that don't interfere with each other (i.e. no globals within the underlying code that need to be altered while running). Critical Section and Mutex based solutions need not apply.
I've so far had experience integrating/using Lua, Squirrel (OO language, based on Lua) and have written an ActionScript 2 virtual machine.
So, what scripting system do you recommend that fits the above criteria? (And if possible, could you also post or link to any comparisons to other scripting languages that you may have)
Thanks,
Grant
Lua has the advantage of being time-tested by a number of big-name video game developers and a good base of knowledgeable developers thanks to Blizzard-Activision's adoption of it as the primary platform for developing World of Warcraft add-ins.
Lua is a very good match for your needs. I'll take them in the same order.
Lua is one of the fastest scripting languages. It's fast to compile and fast to run.
Lua compiles on any platform with an ANSI C compiler, which afaik includes all gaming platforms.
Lua can be pre-compiled, but as a very dynamic languages most errors are only detectable at runtime. Also precompiled code (as bytecode) is often larger in terms of size than source code.
There are many Lua/C++ binding tools.
It doesn't support multi-threading (you cannot access a single instance of the interpreter from multiple threads), but you can have several instances of the interpreter, one per thread, or even one per game object.
Lua have been used in video-game industry for years. Lightweight and efficient.
That being said, ChaiScript and Falcon are good candidates matching your needs and with higher level language than Lua but with less history and community support.
Lua
Boost Python
SWIG
We've had good luck with Squirrel so far. Lua is so popular it's on its way to becoming a standard.
I recommend you worry more about memory than speed. Most scripting languages are "fast enough" and if they get slow you can always push some of that functionality back down into C++. Many of them burn through lots of memory, though, and on a console memory is an even more scarce resource than CPU time. Unbounded memory consumption will crash you eventually, and if you have to allocate 4MB just for the interpreter, that's like having to throw 30 textures out the window to make room.
Lua, and then LuaJIT for extra blaziness!
just don't expect too much from automatic C++ binding libraries, most are slow and restrictive. better do your own binding for your own objects.
as for concurrency, either LuaLanes, or roll your own. if your C++ program is already multithreaded, just call separate LuaStates from each thread, and use your own C++ shared structures as communications channels if needed.
as you might already know, the most often repeated answer in Lua is 'roll your own', and it's often the best advice! except when it's about bindings to common C/C++ libraries, in that case it's quite probable there's already one.
If you haven't looked at it yet I would suggest you check out Angelscript.
I have successfully used it in a cross platform environment (Windows and Linux with only a recompile) and it is designed to integrate well with C++ (both objects and code).
It is lightweight and supports multi-threading (in the sense that the question was asked), performs well and compiles to byte code which could be done in advance.
Start with Python.
If you can prove that you need more speed, then look at Stackless Python. That's what EVE Online uses for their game.
JavaScript may be a reasonable option, because of the mountains of effort that have gone into optimizing the various implementations for use in web-browsers.
These come to mind:
Lua
Python with boost::python
MzScheme or Guile
Ruby with SWIG