分享

Passing C struct pointer to lua script

 quasiceo 2014-01-12

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)

asked Sep 4 '11 at 10:41
user408141
516620

add comment

3 Answers

up vote 4 down vote accepted

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:///ext_ffi_tutorial.html

answered Sep 4 '11 at 13:49
Necrolis
16.9k21649


 
Oh, wow. I didn't know about this. This is definitely the way to go if you are using luajit. –  Tim Sep 8 '11 at 19:30

 
I don't know if this is still true but at one time LuaJIT could not compile pointer <-> light userdata conversions. But it can certainly compile pointer <-> intptr_t conversions. –  finnw Dec 18 '13 at 15:35
add comment

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:

answered Sep 4 '11 at 12:24
BMitch
3,54911118

add comment

The way to do this is with a lua userdata. Here are a couple examples: link, another link.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约