Last active
April 16, 2018 08:03
-
-
Save gavlooth/b7861723998c19ce772112d2874aadf6 to your computer and use it in GitHub Desktop.
A small wrapper that exposes the run_parinfer function from rust-parinfer to lua
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <dlfcn.h> | |
#include "lua.h" | |
#include "lualib.h" | |
#include "lauxlib.h" | |
//We declare a function pointer for the function to import (int myfunction(int) ) | |
typedef const char * (*external_function)(const char *); | |
static int run_parinfer (lua_State *L) { | |
/*Open rust-parinfer shared object library (dynamic) | |
libcparinfer.so must be placed under /user/local/lib. | |
It can be made more flexible using lua/c interop | |
void* dlh = dlopen("/user/local/lib/libcparinfer.so", RTLD_LAZY ); | |
if (dlh == NULL) { | |
fprintf(stderr, "%s", dlerror()); | |
exit(1); | |
} | |
//We resolve the function symbol to use | |
external_function prf = dlsym(dlh, "run_parinfer"); | |
//The string returned from run_parinfer represents a json object | |
const char *json_obj= luaL_checkstring (L, 1); | |
//push the results to lua stack | |
lua_pushstring (L, prf (json_obj)); | |
//return number of results | |
return 1; | |
} | |
static const struct luaL_Reg parinfer_lua_bridge [] = { | |
{"runParinfer", run_parinfer}, | |
{NULL, NULL} /* sentinel */ | |
}; | |
//expose the library to lua | |
int luaopen_parinfer_lua_bridge (lua_State *L){ | |
luaL_newlib(L, parinfer_lua_bridge); | |
return 1; | |
} | |
//Compile with gcc parinfer_lua_bridge.c -shared -o parinfer_lua_bridge.so -ldl -fPIC -llua5.2 -I/usr/include/lua5.2/ | |
//Las line might not be nessesary. Check lua wiki | |
//Minimal test. This is lua code but compiled from fennel programming language | |
/* | |
local mylib = require(("parinfer_lua_bridge")) | |
local json = require(("json")) | |
local ppr = require(("pl.pretty")) | |
local test_me = ({[("mode")] = ("indent"), [("options")] = ({}), [("text")] = ("(defn foo\n [arg\n ret")}) | |
return ppr.dump(mylib.runParinfer(json.encode(test_me))) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment