This article mainly introduced under Linux to write LUA extensions so file and Invoke method instance, this article gives the C language code, compile so file, Lua call code instance, need friends can refer to the following
The code is as follows:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Lua.h"
#include "Lualib.h"
#include "Lauxlib.h"
/* The front declaration of the open function of the library * *
int Luaopen_mylib (lua_state *l);
static int L_sin (Lua_state *l)
{
Double d = Lual_checknumber (L, 1);
Lua_pushnumber (L, sin (d));
printf ("OK now luahook!n");
return 1; /* Number of results * *
}
static const Lual_reg mylib[] =
{
{"Lsin", L_sin},
{NULL, NULL}/* must end with NULL/*
};
int Luaopen_mylib (lua_state *l)
{
Luai_openlib (L, "Mylib", Mylib, 0);
return 1;
}
If you are a. cpp file, be sure to add extern "C" to the Luaopen_mylib, or the exported function will be renamed, remember
Compiling: gcc mylibs.c-fpic-shared-o Libmylib.so-llua
The code is as follows:
Makefile file
CXX =GCC
Libname:=libmylib.so
Hdrname:=mylibs.c
Targetname:=mylibs
cname:=$ (Patsubst%,%.c,$ (TARGETNAME))
oname:=$ (Patsubst%,%.o,$ (TARGETNAME))
All:libmylib
Libmylib: $ (oname)
$ (CXX)-g-shared-wl,$ (libname)
-O $ (libname) $ (oname)-llua
%.O:%.c
$ (CXX)-fpic-c-wall $ (CNAME) clean:$ (RM) *.o *.so
Lua invokes the script:
The code is as follows:
Local one, two, three = Package.loadlib ("libmylib.so", "Luaopen_mylib") ()
Print (Mylib.lsin (10))