如何在Lua中访问C指针

我有一个动态的元素数组在 C 中,我将返回指针。

使用指针,我需要读取这些数组元素的值。

是否有一种函数来从 C 中访问指针并在 Lua 中检索值?

点赞
用户88888888
用户88888888

你可以将这个指针封装到 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);
}
// 表在栈顶

lua_call(L, 1, 0); // 调用 testfunc(t)
2013-05-10 10:34:31
用户577603
用户577603

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];
2013-05-10 10:35:18