Lua loadable c library example (.so)
This commit is contained in:
parent
d089e583cd
commit
c40c698ece
3 changed files with 50 additions and 0 deletions
21
lua_lib/Makefile
Normal file
21
lua_lib/Makefile
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
CC ?= gcc
|
||||||
|
CFLAGS ?= -Wall -O2 -fPIC
|
||||||
|
LDFLAGS ?=
|
||||||
|
|
||||||
|
TARGET = lookup3.so
|
||||||
|
SRC = lua_lookup3.c
|
||||||
|
OBJS = lua_lookup3.o lookup3.o
|
||||||
|
|
||||||
|
all: $(TARGET)
|
||||||
|
|
||||||
|
$(TARGET): $(OBJS)
|
||||||
|
$(CC) -shared -o $@ $^ $(LDFLAGS)
|
||||||
|
|
||||||
|
lua_lookup3.o: $(SRC)
|
||||||
|
$(CC) $(CFLAGS) -c -o $@ $<
|
||||||
|
|
||||||
|
lookup3.o: ../lookup3.c
|
||||||
|
$(CC) $(CFLAGS) -c -o $@ $<
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -f $(TARGET) $(OBJS)
|
||||||
2
lua_lib/driver.lua
Normal file
2
lua_lib/driver.lua
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
local myhash = require "lookup3"
|
||||||
|
print(myhash.lookup3("hello", 0) % 100)
|
||||||
27
lua_lib/lua_lookup3.c
Normal file
27
lua_lib/lua_lookup3.c
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
#include <lua.h>
|
||||||
|
#include <lauxlib.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
uint32_t lookup3(const void *key, size_t length, uint32_t initval);
|
||||||
|
|
||||||
|
// Lua wrapper
|
||||||
|
static int l_lookup3(lua_State *L) {
|
||||||
|
size_t len;
|
||||||
|
const char *str = luaL_checklstring(L, 1, &len); // get string + length
|
||||||
|
uint32_t initval = (uint32_t)luaL_checkinteger(L, 2); // get initval
|
||||||
|
|
||||||
|
uint32_t hash = lookup3(str, len, initval);
|
||||||
|
|
||||||
|
lua_pushinteger(L, hash); // return the hash
|
||||||
|
return 1; // number of return values
|
||||||
|
}
|
||||||
|
|
||||||
|
// Module open function
|
||||||
|
int luaopen_lookup3(lua_State *L) {
|
||||||
|
lua_newtable(L);
|
||||||
|
|
||||||
|
lua_pushcfunction(L, l_lookup3);
|
||||||
|
lua_setfield(L, -2, "lookup3");
|
||||||
|
|
||||||
|
return 1; // return the table
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue