2013-05-10 96 views
1

我在C中有一個元素數組(動態),我將作爲指針返回。如何訪問Lua中的C指針

使用指針我需要讀取這些數組元素的值。

是否有任何函數可以從C中訪問指針並在Lua中檢索值?

回答

5

您可以將此指針包裝到userdata中,並寫入存取器方法(複雜性:高)。更簡單的解決方案是將該數組轉換爲常規的Lua表。

size_t arr_size = 10; 
int arr[10] = { 0 }; 

lua_getglobal(L, "testfunc"); 

lua_createtable(L, arr_size, 0); 
for (size_t i = 0; i < arr_size; i++) { 
    lua_pushinteger(L, arr[i]); 
    lua_rawseti(L, -2, i+1); 
} 
// the table is at top of stack 

lua_call(L, 1, 0); // call testfunc(t) 
3

Lua中沒有陣列的概念作爲從C.

返回一個C-指針到Lua通常在不透明userdata對象的形式完成的,其然後依次被傳遞已知額外地暴露功能來檢索具體的數據:

local array = your_function_returning_a_pointer(); 
assert(type(array) == "userdata"); 

local index = 1; 
local obj = get_object_from_array(array, index); 

或者,暴露到Lua一個函數,返回對象的一個​​表:

local objects = your_function_now_returning_a_table(); 
assert(type(objects) == "table"); 

local index = 1; 
local obj = objects[1];