# Include <stdio. h>
# Include <stdlib. h>
# Include <ctype. h>
# Include <errno. h>
# Include <string. h>
# Include <unistd. h>
# Include <fcntl. h>
# Include <sys/stat. h>
# Include <limits. h>
# Include <math. h>
# Include "lua. h"
# Include "lualib. h"
# Include "lauxlib. h"
/* Pre-declaration of the open function 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 is 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;
}
For the. cpp file, add extern "C" to luaopen_mylib; otherwise, the exported function will be renamed. Remember
Compile: gcc mylibs. c-fPIC-shared-o libmylib. so-llua
Makefile
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 call script:
Local One, Two, Three = package. loadlib ("libmylib. So", "luaopen_mylib ")()
Print (mylib. lsin (10 ))