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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(<ime); | |
return ctime(<ime); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%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(); |
% 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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package.loadlib('./example.so', 'luaopen_example')() | |
print(example.My_variable) | |
print(example.fact(5)) | |
print(example.my_mod(5, 3)) | |
print(example.get_time()) |
When run, this is the output:
% lua test.lua
3
120
2
Wed Jun 14 14:56:54 2017
% lua test.lua
3
120
2
Wed Jun 14 14:56:54 2017
Hope this helps the world. :)
No comments:
Post a Comment