local ffi = require('ffi')
ffi.cdef([[
void test(char **out);
void free(void *ptr);
]])
--test.so中包含c语言实现的test函数
local clib = ffi.load('./test.so')
function destory(obj)
ffi.C.free(obj[0])
end
local out = ffi.new('char *[0]')
clib.test(out)
ffi.gc(out, destory)
print(ffi.string(out[0]))
这样写才能保证内存不泄露。
luajit文档里关于GC有两段描述:
1. All explicitly (ffi.new(), ffi.cast() etc.) or implicitly (accessors) created cdata objects are garbage collected. 2. Memory areas returned by C functions (e.g. from malloc()) must be manually managed, of course (or use ffi.gc()). Pointers to cdata objects are indistinguishable from pointers returned by C functions (which is one of the reasons why the GC cannot follow them).
文档里说ffi.new创建的对象是由LuaJIT托管GC,但又说通过malloc创建的需要手动管理GC,我知道C函数中malloc后return返回的内存指针需要ffi.gc,那么如下情况中out是否需要ffi.gc,还是LuaJIT会托管GC?
--[[
void test(char **out) {
*out = malloc(10);
const char *b = "abcdefg";
memcpy(*out, b, sizeof(b));
}
--]]
local ffi = require('ffi')
ffi.cdef([[
void test(char **out);
void free(void *ptr);
]])
--test.so中包含c语言实现的test函数
local clib = ffi.load('./test.so')
function destory(obj)
ffi.C.free(obj[0])
end
local out = ffi.new('char *[0]')
--local out = ffi.gc(ffi.new('char *[0]'), destory)
clib.test(out)
print(ffi.string(out[0]))
--