问题描述
Lightuserdata与userdata不同,该怎么办?我的意思是lua中的lightuserdata操作.看来我无法将其转换为任何其他数据类型.
Lightuserdata is different from userdata so what can I do with it? I mean the operations of lightuserdata in lua. Looks like I cannot convert it to any other data type.
我的一个案例:
我的 C 库向 Lua 返回了一个名为c_pointer"的 C 指针,AKA lightuserdata,然后我想要:
My C library returns a C pointer named 'c_pointer', AKA lightuserdata to Lua, and then I want:
my_pointer = c_pointer +4
my_pointer = c_pointer +4
,然后将"my_pointer"传递回C库.由于我无法对"c_pointer"执行任何操作,因此表达式"c_pointer + 4"无效.
and then pass 'my_pointer' back to C library. Since I cannot do anything with 'c_pointer', so the expression 'c_pointer + 4' is invalid.
我想知道对此有一些切实可行的解决方案吗?
I am wondering are there some practical solutions to this?
推荐答案
Lightuserdata由C库创建.它们只是C指针.
Lightuserdata are created by C libraries. They are simply C pointers.
例如,您可以使用它们来引用使用 malloc
分配的数据,或在模块中静态分配的数据.您的C库可以使用 lua_pushlightuserdata
将这些指针作为lightuserdata传递到Lua端,然后Lua可以将其返回给堆栈上的库(或其他C代码).Lua代码可以将lightuserdata用作任何其他值,例如将其存储在表中,甚至用作表键.
For example, you can use them to refer to data you allocate with malloc
, or statically allocate in your module. Your C library can transfer these pointers to the Lua side as a lightuserdata using lua_pushlightuserdata
, and later Lua can give it back to your library (or other C code) on the stack. Lua code can use the lightuserdata as any other value, storing it in a table, for example, even as a table key.
附录
要回答您的修订问题,如果要向指针添加偏移量,请在C侧执行.将lightuserdata和整数偏移量传递给C,然后让C使用 ptr [n]
To answer your revised question, if you want to add an offset to the pointer, do it on the C side. Pass the lightuserdata and the integer offset to C, and let C do the offset using ptr[n]
void * ptr = lua_touserdata(L, idx1);
lua_Integer n = lua_tointeger(L. idx2);
// do something with
((char *)ptr)[n];
这篇关于是否有内置例程将lightuserdata转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!