First, we define the C++ struct in the header file, example.hpp:
The struct implementation is defined in example.cpp:
We then define the interface file, example.i, to be used by SWIG:
After which, we use SWIG to generate the wrapper file:
% swig -lua -c++ example.i
We then compile the C++ source files and create the shared object to be used by our Lua script:
% g++ -fPIC -I/usr/include/lua5.2 -c example_wrap.cxx -o example_wrap.o
% g++ -fPIC -c example.cpp -o example.o
% g++ -shared -I/usr/include/lua5.2 example.o example_wrap.o -o example.so
We then write a Lua script, test.lua, for testing:
When run:
Lines 20-24 of test.lua print the names of the fields of the struct. Note that the order of the printing of the field names (lines 21-22 of output.txt) may not be the same as the order of declaration of the fields in the C++ struct definition in example.hpp (lines 3-4).
Lines 26-30 print the names of the methods of the struct.
Hope this helps the world.