From 55f298d24906aa9c91e40bc91027bf31bb69fb06 Mon Sep 17 00:00:00 2001 From: lxsang Date: Wed, 8 May 2019 18:49:40 +0200 Subject: [PATCH] fix some stuff --- lib/ffi/example/example.lua | 9 +++++++++ lib/ffi/example/lib.c | 6 ++++++ lib/ffi/ffi.c | 25 +++++++++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/lib/ffi/example/example.lua b/lib/ffi/example/example.lua index f4ae5ce..6bf01af 100644 --- a/lib/ffi/example/example.lua +++ b/lib/ffi/example/example.lua @@ -55,6 +55,15 @@ if lib then end + + + fn = FFI.lookup(lib, "buff") + if(fn) then + local ptr = FFI.call(FFI.atomic(FFI.type.POINTER),{}, fn, {}) + echo(FFI.string(ptr)) + + end + FFI.unloadAll() end echo("end the day") \ No newline at end of file diff --git a/lib/ffi/example/lib.c b/lib/ffi/example/lib.c index caef882..ebf2e6f 100644 --- a/lib/ffi/example/lib.c +++ b/lib/ffi/example/lib.c @@ -1,5 +1,6 @@ #include +char data[] = {'h', 'e','l', 'l', 'o'}; typedef struct{ char a; @@ -31,4 +32,9 @@ void test_string(char* buff, const char* a) { sprintf(buff,"you say %s", a); printf("%s\n", buff); +} + +char * buff() +{ + return data; } \ No newline at end of file diff --git a/lib/ffi/ffi.c b/lib/ffi/ffi.c index c6f0502..4af2c8c 100644 --- a/lib/ffi/ffi.c +++ b/lib/ffi/ffi.c @@ -529,6 +529,18 @@ static int l_ffi_offset(lua_State* L) lua_pushnil(L); return 1; } +static int l_ffi_byte_at(lua_State* L) +{ + void* ptr = lua_touserdata(L, 1); + int off = luaL_checkinteger(L,2); + if(ptr) + { + lua_pushnumber(L, *((uint8_t*)(ptr + off))); + return 1; + } + lua_pushnil(L); + return 1; +} static int l_ffi_string(lua_State* L) { void* ptr = lua_touserdata(L,1); @@ -546,6 +558,16 @@ static int l_ffi_free(lua_State* L) lua_pushboolean(L, 1); return 1; } +static int l_ffi_bytearray(lua_State* L) +{ + void* ptr = lua_touserdata(L,1); + int size = luaL_checknumber(L,2); + //create new bytearray + lua_new_byte_array(L,size); + byte_array_t *ba = l_check_barray(L,-1); + memcpy(ba->data, ptr, size); + return 1; +} static const struct luaL_Reg _lib [] = { {"dlopen", l_dlopen}, {"dlsym",l_dlsym}, @@ -556,8 +578,11 @@ static const struct luaL_Reg _lib [] = { {"new", l_ffi_new}, {"meta", l_ffi_meta}, {"at", l_ffi_offset}, + {"byteAt", l_ffi_byte_at}, // special case: pointer to string {"string", l_ffi_string}, + // pointer to byte array + {"bytearray", l_ffi_bytearray}, {"free", l_ffi_free}, {NULL,NULL} };