Wednesday, June 14, 2017

SWIG for Lua: Class demonstration

In this entry, we demonstrate how to expose a C++ class to Lua using SWIG. The environment I use is Ubuntu 16.04.

First, we define the C++ class in example.hpp:

class MyClass
{
public:
MyClass(int a, int b);
void greet();
private:
int x;
int y;
};
view raw example.hpp hosted with ❤ by GitHub
The class implementation is defined in example.cpp:

#include <example.hpp>
#include <ctime>
#include <cstdio>
MyClass::MyClass(int a, int b): x(a), y(b) {}
void MyClass::greet()
{
printf("Hello, world: x=%d y=%d\n", x, y);
}
view raw example.cpp hosted with ❤ by GitHub
Then, we define the interface file, example.i, to be used by SWIG:

%module example
%{
/* Includes the header in the wrapper code */
#include "example.hpp"
%}
/* Parse the header file to generate wrappers */
%include "example.hpp"
view raw example.i hosted with ❤ by GitHub
We then use SWIG to generate the wrapper file, example_wrap.cxx:

% swig -lua -c++ example.i

Next, we compile the C++ source files:

% g++ -fPIC -I/usr/include/lua5.2 -c example_wrap.cxx -o example_wrap.o
% g++ -fPIC -I. -c example.cpp -o example.o

Then, we create the shared object, example.so:

% g++ -shared -I/usr/include/lua5.2 example_wrap.o example.o -o example.so

We write a Lua script to test if SWIG works:

#!/usr/bin/lua
package.loadlib('./example.so', 'luaopen_example')()
A = example.MyClass(6, 7)
A:greet()
view raw test.lua hosted with ❤ by GitHub
When run:

% ./test.lua
Hello, world: x=6 y=7

Hope this helps the world.

No comments:

Post a Comment