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:

The class implementation is defined in example.cpp:

Then, we define the interface file, example.i, to be used by SWIG:

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:

When run:

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

Hope this helps the world.

No comments:

Post a Comment