We first start with the C++ header file:
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
extern double My_variable; | |
int fact(int n); | |
int my_mod(int x, int y); | |
char *get_time(); |
We then create the C++ implementation file:
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.hpp> | |
#include <ctime> | |
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.hpp" | |
%} | |
/* Parse the header file to generate wrappers */ | |
%include "example.hpp" |
% swig -lua -c++ example.i
Notice the use of the -c++ argument.
Next, we compile the wrapper file:
% g++ -fPIC -I/usr/include/lua5.2 -c example_wrap.cxx -o example_wrap.o
Notice that the generated wrapper file has the file suffice .cxx
We then compile the C++ implementation file:
% g++ -fPIC -I. -c example.cpp -o example.o
Finally, we create the shared object to be used by our Lua script:
% g++ -shared -I/usr/include/lua5.2 example_wrap.o example.o -o example.so
We write a Lua script for testing:
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 16:41:11 2017
Hope this helps the world. :)
No comments:
Post a Comment