英文:
How can I get char* using lua ffi
问题
我想使用luajit ffi
来调用c
函数。现在我有一个在so
文件中的函数,这个函数将一个值分配给一个char*
,就像这样:
typedef struct MyStruct_s {
int a;
} MyStruct;
void *init(char* host, int timeout)
{
void *handle = (void*)malloc(sizeof(MyStruct));
if (handle == NULL) {
printf("create myStruct failed\n");
}
return handle;
}
int get_value(void *handle, char *buffer, int *len) // 我想要将buffer的值传递给lua
{
MyStruct* my_handle = (MyStruct*)handle;
// my_handle 做一些事情
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;
}
我如何在Lua中获取get_value
函数中的buffer
值?我尝试了这样的方式:
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}) -- 这样做对吗?
local len = 1024;
local node_len = ffi.cast("int *", len)
local node_exist = zkclient.get_value(handle, node_value, node_len)
但是它不起作用,我如何将get_value
函数中的buffer
传递到Lua中?
英文:
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
?
答案1
得分: 0
你可以传递一个与相同数据类型的指针相反的数组。
local function zk_get_value() -- 返回 Lua 字符串
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论