繁体   English   中英

如何在Lua中访问C指针

[英]How to access C pointers in Lua

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

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

是否有任何函数可以从C访问指针并在Lua中检索值?

您可以将此指针包装到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)

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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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