First, we define the C++ class in example.hpp:
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
class MyClass | |
{ | |
public: | |
MyClass(int a, int b); | |
void greet(); | |
private: | |
int x; | |
int y; | |
}; |
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> | |
#include <cstdio> | |
MyClass::MyClass(int a, int b): x(a), y(b) {} | |
void MyClass::greet() | |
{ | |
printf("Hello, world: x=%d y=%d\n", x, y); | |
} |
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
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:
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
#!/usr/bin/lua | |
package.loadlib('./example.so', 'luaopen_example')() | |
A = example.MyClass(6, 7) | |
A:greet() |
% ./test.lua
Hello, world: x=6 y=7
Hope this helps the world.
No comments:
Post a Comment