We begin with the files needed starting with the header file, example.h:
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
double My_variable; | |
int fact(int n); | |
int my_mod(int x, int y); | |
char *get_time(); |
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 <example.h> | |
#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 | |
%{ | |
/* Includes the header in the wrapper code */ | |
#include "example.h" | |
%} | |
/* Parse the header file to generate wrappers */ | |
%include "example.h" |
We then call SWIG to create the wrapper file, example_wrap.c:
% swig -lua example.i
Then we compile the generated wrapper file:
% gcc -fPIC -I/usr/include/lua5.2 -c example_wrap.c -o example_wrap.o
We also compile the C source file, example.c:
% gcc -fPIC -I. -c example.c -o example.o
Finally, we create the shared object which is to be used by our Lua script:
% gcc -shared -I/usr/include/lua5.2 example_wrap.o example.o -o example.so
The Lua script is just the same as our previous blog entry. For convenience:
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()) |
% lua test.lua
3
120
2
Wed Jun 14 14:56:54 2017
3
120
2
Wed Jun 14 14:56:54 2017
Hope this helps the world. :)
No comments:
Post a Comment