将 C 结构指针传递给 lua 脚本
我想知道有没有办法将结构指针传递给lua脚本, 并从 lua 访问它的成员而无需复制(用于读写目的)。
那么,例如是否可以直接通过其指针覆盖 ac 结构的成员?
(我使用的是luajit)
I would like to know is there a way to pass a struct pointer to a lua script,
and reach it's members from lua without copy (for read and write purposes).
So, for example is it possible to overwrite a member of a c struct directly through of its pointer?
(I am using luajit)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了蒂姆的回答之外,您还可以选择轻用户数据。您最终不会在 Lua 堆栈中得到数据的副本,您推送到 Lua 的只是一个指针。
Lua 不了解该指针中的内容,它是否仍然指向有效内存,或者如何访问该指针中的任何对象,因此您必须在 C 中自己处理所有这些。我通常发送一个指针到列表上的项目,因此如果存在从列表中删除条目的任何风险,我首先迭代列表以验证指针(如果列表很短,这没什么大不了的)。要在 Lua 中访问指针内的项,您需要用 C 编写可以从 Lua 调用的 get/set 函数。
首先,以下是有关推送和检索 lightuserdata 的条目:
In addition to Tim's answer, you can also go for light userdata. You don't end up with a copy of your data in the Lua stack, all you push to Lua is a pointer.
Lua has no understanding of what is in this pointer, whether it still points to valid memory, or how to access any objects in this pointer, so you'll have to handle all of this yourself in C. I am usually sending a pointer to an item on a list, so if there's any risk that entry has been deleted from the list, I first iterate over the list to validate the pointer (not a big deal if your lists are short). To access items within the pointer in Lua, you need to write get/set functions in C that you can call from Lua.
To get started, here are the entries on pushing and retrieving the lightuserdata:
鉴于您已将其标记为 luajit,您可以将轻用户数据(如其他人提到的)与 FFI 结合起来以进行直接结构成员访问,请参阅此处的教程:http://luajit.org/ext_ffi_tutorial.html
Seeing as you have tagged this for luajit, you can combine the light userdata (as mentioned by others) with FFI for direct struct member access, see the tutorial here: http://luajit.org/ext_ffi_tutorial.html
做到这一点的方法是使用 lua userdata。以下是几个示例:链接、另一个链接。
The way to do this is with a lua userdata. Here are a couple examples: link, another link.