Passing C struct pointer to lua script
Asked Answered
T

3

6

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)

Tamas answered 4/9, 2011 at 10:41 Comment(0)
T
5

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

Transcendental answered 4/9, 2011 at 13:49 Comment(1)
Oh, wow. I didn't know about this. This is definitely the way to go if you are using luajit.Shook
S
6

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:

Saretta answered 4/9, 2011 at 12:24 Comment(0)
T
5

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

Transcendental answered 4/9, 2011 at 13:49 Comment(1)
Oh, wow. I didn't know about this. This is definitely the way to go if you are using luajit.Shook
S
1

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

Shook answered 4/9, 2011 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.