简体   繁体   中英

How to access C pointers in Lua

I have an array of elements (dynamic) in C which I will return as a pointer.

Using the pointer I need to read the value of those array elements.

Is there any function to access pointers from C and retrieve the value in Lua.?

You can wrap this pointer into userdata and write accessor methods (complexity: high). Easier solution is to convert that array to regular Lua table.

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)

Lua does not have the concept of arrays as known from C.

Returning a C-pointer to Lua is usually done in the form of an opaque userdata object, which can then in turn be passed to additionally exposed functions to retrieve concrete data:

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

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

Alternatively, expose a function to Lua that returns a table of objects:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM