sonoro1234 / LuaJIT-ImGui

LuaJIT ffi binding for imgui, backends and extension widgets
MIT License
213 stars 29 forks source link

Unable to call function with array parameter #28

Closed fastcoding closed 2 years ago

fastcoding commented 2 years ago

Some functions with array argument is not callable through generic version due to its ffi ctype is invalid, for example,

function M.Combo(a1,a2,a3,a4,a5,a6) -- generic version
    if (ffi.istype('const char* const[]',a3) or ffi.istype('const char const[]',a3) or ffi.istype('const char const[][]',a3)) then return M.Combo_Str_arr(a1,a2,a3,a4,a5) end
    if (ffi.istype('const char*',a3) or type(a3)=='string') then return M.Combo_Str(a1,a2,a3,a4) end
    if ffi.istype('bool(*)(void* data,int idx,const char** out_text)',a3) then return M.Combo_FnBoolPtr(a1,a2,a3,a4,a5,a6) end
    print(a1,a2,a3,a4,a5,a6)
    error'M.Combo could not find overloaded'
end

Creating any instance of array with unknown size from ffi will lead to error, for example,

 t0=ffi.typeof('char []')
 p=ffi.new('char[1]')
 print(ffi.istype(t0,p)) -- output false
 q=t0(). -- error

How about replace all [] with *?

sonoro1234 commented 2 years ago
--string
local ffi = require"ffi"
t0=ffi.typeof('char []')
p=ffi.new('char[?]',1)
print(ffi.istype(t0,p),p) -- output true
------------------------------
--string array
-- keep strings assigned in anchors to avoid __gc
local anchors = {}
local strs = {"one","two","three"}
local Items = ffi.new("const char*[?]",#strs)
for i = 0,#strs-1  do
    anchors[#anchors+1] = ffi.new("const char*",strs[i+1])
    Items[i] = anchors[#anchors]
end
print(Items)
sonoro1234 commented 2 years ago

use case: https://github.com/sonoro1234/LuaJIT-rtaudio/blob/bda51c201586adefbb9640237953c20eaf11dfd7/samples/multi_sndfile_player_imgui_window.lua#L138

fastcoding commented 2 years ago

thanks a lot, the [?] solved my issue!