Whenever programmers talk about programming languages, and how amazing those new languages are, they always end that discussion with how kick-ass C still is! It’s amazing how this primitive language is still at large and being used throughout the industry.
While working on my game, I have built the core artificial intelligence in C for maximum performance, and boy let me tell you … That increased the performance by orders of magnitude.
Performance wasn’t the only benefit I got from using C. Believe it or not, portability was another great feature, and the fact that I am using Unity to develop my game now didn’t change the fact that the AI is still written in C. Using C# and C in Unity has to be credited to SWIG, the star of our show tonight, so let’s see what that’s all about.
SWIG: Something Wonderful In Gloves
SWIG is actually a very simple tool as a concept, but the value it offers is just too great. The basic idea is, integrating your C/C++ code with (almost) any other language.
You see, most languages support calling C libraries natively, because C is the king that they turn back to when raw power is requried. Python has ctypes, C# has Marshaling, Java has JNI, ObjC just works with C, and so on… So, where does SWIG fit in that picture?
SWIG tells you as a developer, define the interface of your C/C++ library in a *.i file, and I’ll do the rest. Whoa! What about all that horrible JNI code I had to write? What about those weird marshaling rules C# requires? Nil of that is required… Sweet!
SWIG holds true to that (for C at least). I have simplified the interface of my AI a bit, and defined a very simple *.i file:
Yup, that was it. All I had to do then was run SWIG, and tell it that I want to be able to use this library from CSharp, and it replied, “Your command is my output”.
There isn’t really much else to cover. SWIG gave me all the CSharp files I needed to use the library, and I simply linked the library and dropped the CSharp files into my project. Everything was fly!
I guess if you ever had doubts about what game engine you’ll use, or what language you’ll be developing on as you write some core functionality, just keep in mind that C is there for you. Sure, it may not have Generics, dynamic collections, and other basic features, but it wasn’t so bad writing all those linked lists in pure C! lol, I’ll probably switch them later to a better dynamic array implementation, but for now, this will do.