lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tuesday 10, Kaj Eijlers wrote:
> Hi,
> God I love LuaJit. Sliced bread can finally retire.
> However.....
> 
> I am trying to do some openGL, which works like a charm, but I've ran into
> a problem. I'm sure it's me but I can't figure it out.
> 
> I need to pass in a pointer to an array of structs, which poses no problem,
> 
>   typedef struct
>   {
>    float u;
>    float v;
>   } TexCoords;
>   typedef struct
>   {
>    float x;
>    float y;
>   } Positions;
>   typedef unsigned int Colors;
>   typedef struct
>   {
>    Positions Position;
>    TexCoords TexCoord;
>    Colors Color;
>   } PTC;
> 
> Creating an array of those with
> 
> local verts = ffi.new("PTC[3]")
> local vertOffs = verts
> 
> sending the pointer off:
>   gl.glVertexPointer(2, gl.GL_FLOAT, ffi.sizeof("PTC"), vertoffs);
> Works like a charm, the sizeof is the stride, vertoffs the pointer
> (although I am not sure if I created a copy when I assigned to 'verts')

I think 'vertOffs' is the same value as 'verts', so no copy.

> 
> Now I need to pass a pointer to a member inside PTC, in this case TexCoords
> which would be at offset 8.
> Try as I might I can't create a pointer to it.
> 
> I tried
> local tex = verts + 8 but that doesn't work
> I tried
> local ptr = ffi.new("unsigned char*")
> ptr = verts
> ptr = ptr + 8
> 
> But it doesn't do what I expect.

It might help if you show an example in C code of what you are trying to do.

Also "verts + 8" in Lua, should be the same as "&verts[8]" in C.  So 'tex' 
would be a pointer to the 8th element of the verts array (which only has 3 
elements?).

You might be able to do what you really need with just this:
verts[0].TexCoord

But if you really need a pointer to the field of a struct, then something like 
this might work:
-- get byte pointer to first array element
local ptr = ffi.cast("unsigned char*", verts[0])
-- get field's byte offset.
local field_offset = ffi.offsetof("PTC", "TexCoord");
-- cast pointer to field back to correct type.
local tex = ffi.cast("TexCoords *", ptr + field_offset);


-- 
Robert G. Jakabosky