Created
June 2, 2018 18:37
-
-
Save ultimateprogramer/488130bb73ea1120ec65041d1db8b566 to your computer and use it in GitHub Desktop.
Exposing C Functions to Lua - https://chsasank.github.io/lua-c-wrapping.html
This file contains hidden or 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
| gcc main.c -shared -o mylib.so -fPIC -llua |
This file contains hidden or 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
| #ifdef __cplusplus | |
| #include "lua.hpp" | |
| #else | |
| #include "lua.h" | |
| #include "lualib.h" | |
| #include "lauxlib.h" | |
| #endif | |
| #include <math.h> | |
| //so that name mangling doesn't mess up function names | |
| #ifdef __cplusplus | |
| extern "C"{ | |
| #endif | |
| static int c_swap (lua_State *L) { | |
| //check and fetch the arguments | |
| double arg1 = luaL_checknumber (L, 1); | |
| double arg2 = luaL_checknumber (L, 2); | |
| //push the results | |
| lua_pushnumber(L, arg2); | |
| lua_pushnumber(L, arg1); | |
| //return number of results | |
| return 2; | |
| } | |
| static int my_sin (lua_State *L) { | |
| double arg = luaL_checknumber (L, 1); | |
| lua_pushnumber(L, sin(arg)); | |
| return 1; | |
| } | |
| //library to be registered | |
| static const struct luaL_Reg mylib [] = { | |
| {"c_swap", c_swap}, | |
| {"mysin", my_sin}, /* names can be different */ | |
| {NULL, NULL} /* sentinel */ | |
| }; | |
| //name of this function is not flexible | |
| int luaopen_mylib (lua_State *L){ | |
| luaL_newlib(L, mylib); | |
| return 1; | |
| } | |
| #ifdef __cplusplus | |
| } | |
| #endif |
This file contains hidden or 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
| mylib = require 'mylib' | |
| print(mylib.c_swap(2, 4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment