luaffikongopenrestyluajit

How can I get char* using lua ffi


I want to use luajit ffi to call c function. Now I have a function in so file, this function assigns a value to a char*, such as this:

typedef struct MyStruct_s {
    int a;
}MyStruct;
void *init(char* host, int timeout) 
{
    void *handle = (void*)malloc(MyStruct);
    if(handle == NULL) {
        printf("create myStruct falied\n");
    }

    return handle;
}
int get_value(void *handle, char *buffer, int *len) // I want to get buffer to lua
{
    MyStruct* my_handle = (MyStruct*)handle;
    // my_handle do something
    if(buffer == NULL) {
        printf("buffer is NULL\n");
        return -1;
    }
    char tmp[10] = "hi there";
    memcpy(buffer, tmp, strlen(tmp));
    *len = strlen(tmp);

    return 0;
}

How can I get buffer value in lua? I tried this

local zkclient = ffi.load("zkclient")   
ffi.cdef [[
void *init();
int get_value(void *zkhandle, char *buffer, int *len);
]]
local handle = zkclient.init()
if handle == nil then
    kong.log.info("handle is nil ")
    return nil
end

local node_value = ffi.new('char[1024]', {0})  // is it right to do this?
local len = 1024;
local node_len = ffi.cast("int *", len)
local node_exist = zkclient.get_value(handle, node_value, node_len)

but it do not work, how can I get buffer from get_value to lua?


Solution

  • You can pass an array instead of a pointer of the same datatype.

    local function zk_get_value()  -- returns Lua string
       local node_value = ffi.new('char[?]', 1024)
       local node_len = ffi.new('int[1]', 1024)
       zkclient.get_value(handle, node_value, node_len)
       return ffi.string(node_value, node_len[0])   
    end