lua-users home
lua-l archive

Re: LuaJIT FFI simple binding problem

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 2012年02月21日 11:42, Olivier Goudron wrote:
I am testing LuaJIT FFI binding and i have a problem with this code :
****
local ffi = require("ffi")
ffi.cdef[[
struct slice{
 char *data;
 int len;
};
]]
local sk = ffi.new("struct slice")
sk.len = 3
sk.data = "key"
print(sk.len)
print(ffi.string(sk.data))
****
The last line cause LuaJIT to crash and the "sk.data = "key" assignement
complain with this message : cannot convert 'string' to 'char *'
LuaJIT is telling you what the problem is: you cannot just
assign a Lua string to a char* ctype. You need to allocate
the necessary memory and use ffi.copy.
tl;dr: replace the line:
 sk.data = "key"
by something like:
 sk.data = ffi.new("char[4]")
 ffi.copy(sk.data,"key")
--
Pierre 'catwell' Chapuis

AltStyle によって変換されたページ (->オリジナル) /