Wednesday, June 14, 2017

Compiling and running SWIG for Lua in Ubuntu 16.04

As a disclaimer, this blog entry is adapted from:

http://www.swig.org/tutorial.html
http://www.swig.org/Doc2.0/Lua.html#Lua_nn5

Let's begin. first, you need to have SWIG installed:

% sudo apt-get install swig

You also need to have Lua installed. Say, Lua 5.2:

% sudo apt-get install lua5.2

Let us consider the following file, example.c, whose functions and variable we wish to use in Lua:

#include <time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(&ltime);
return ctime(&ltime);
}
view raw example.c hosted with ❤ by GitHub
Then, we need to create an interface file, say, example.i:

%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
view raw example.i hosted with ❤ by GitHub
After creating the files, we use SWIG to create a wrapper file:

% swig -lua example.i

This creates a wrapper file named example_wrap.c.

Now it is time to compile the C files:

% gcc -fPIC -I/usr/include/lua5.2 -c example_wrap.c -o example_wrap.o
% gcc -fPIC -c example.c -o example.o

Then we create the shared object which shall be used by our Lua script:

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

This creates the shared object, example.so.

Finally, we create our Lua script to test if Lua can call the C functions and variable:

package.loadlib('./example.so', 'luaopen_example')()
print(example.My_variable)
print(example.fact(5))
print(example.my_mod(5, 3))
print(example.get_time())
view raw test.lua hosted with ❤ by GitHub

When run, this is the output:

% lua test.lua
3
120
2
Wed Jun 14 14:56:54 2017

Hope this helps the world. :)

No comments:

Post a Comment