lualuajit

How to get the value of char* in lua


I am tring to call c function in lua, the c function is in a so file and code is like this:

typedef struct attributes_s {
    char name[256];
    char id[256];
}attributes_t

int get_service_instances(attributes_t **array, size_t *service_nums);

This function will assign a value to array and service_nums, array may have several instances of attributes_t, right now I only have it return one. lua code is like this

local ffi_Cli = ffi.load("client")

ffi.cdef[[
typedef struct attributes_s {
    char name[256];
    char id[256];
}attributes_t

int get_service_instances(attributes_t **array, size_t *service_nums);
]]
local get_services_result = ffi.new("attributes_t*[1]")
local res_len = ffi.new("size_t[1]")
if ffi_Cli.get_service_instances(get_services_result, res_len) ~= 0 then
  print("get failed")
  return
end
print(get_services_result[1].name)  -- get cdata<char (&)[256]> 
print(ffi.string(get_services_result[1].name, 256))  -- get coredump

If I use ffi.string(get_services_result[1].name, 256) or change 256 to other number, it will coredump, the gdb bt is like this

#0  0x00007f55a558cff1 in __strlen_sse2_pminub () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-222.el7.x86_64 libgcc-4.8.5-28.el7.x86_64 libstdc++-4.8.5-28.el7.x86_64 libuuid-2.23.2-52.el7.x86_64 libyaml-0.1.4-11.el7_0.x86_64 nss-softokn-freebl-3.34.0-2.el7.x86_64 sssd-client-1.16.0-19.el7.x86_64 zlib-1.2.7-17.el7.x86_64
(gdb) bt
#0  0x00007f55a558cff1 in __strlen_sse2_pminub () from /lib64/libc.so.6
#1  0x00007f55a78a64a6 in lj_cf_ffi_string (L=0x7f55a831a380) at lib_ffi.c:691

I donot know how can I get the value of attributes_t, why can not I get char* using ffi.string()


Solution

  • I changed 1 to 0 like this get_services_result[0].name and it works. But doesn't subscript in lua start from 1?