RE: FFI and return struct by value

  • From: William Adams <william_a_adams@xxxxxxx>
  • To: "luajit@xxxxxxxxxxxxx" <luajit@xxxxxxxxxxxxx>
  • Date: Tue, 6 Aug 2013 19:03:38 -0700

Vector2_new() returns what?

In general, you should be returning some heap allocated thing.

Sent from my Windows Phone
________________________________
From: Aaron Bolyard<mailto:bolyard.aaron@xxxxxxxxx>
Sent: ‎8/‎6/‎2013 1:42 PM
To: luajit@xxxxxxxxxxxxx<mailto:luajit@xxxxxxxxxxxxx>
Subject: FFI and return struct by value

Hello,

I have the following function:

extern "C"
__declspec(dllexport) holo::Vector2 holo_Vector2_obj_new(float x, float y)
{
    holo::Vector2 _value(x, y);
    return _value;
}

And I declare it via FFI as so:

ffi.cdef[[
typedef struct holo_Vector2
{
    float x;
    float y;
} holo_Vector2;
holo_Vector2 holo_Vector2_obj_new(float x, float y);]]

Both structures are the same size (as in C++ and FFI): just a simple
two component vector.

I call the function like so in Lua:

local value = ffi.C.holo_Vector2_obj_new(1, 2)

However, it crashes and the stack is odd:

Program received signal SIGSEGV, Segmentation fault.
0x004067ef in holo::Vector2::Vector2 (this=0x3f800000, x=2, y=0)
    at source/math/vector2.cpp:14
14              this->x = x;
(gdb) bt
#0  0x004067ef in holo::Vector2::Vector2 (this=0x3f800000, x=2, y=0)
    at source/math/vector2.cpp:14
#1  0x0040ece0 in holo_Vector2_obj_new (x=2, y=0)
    at source/wrapper/wrapper.cpp:422

I'm thinking it's an issue with returning a struct by value, from what
I've read about the cdecl calling convention. I noticed that the this
pointer in the constructor is really the hexadecimal representation of
1.0 (in floating point), which happens to be the first argument.
Changing the first argument changes the this pointer value as well.

So, how can I bind a function that returns a structure by value? I
have quite a few methods that return small structures by value.

LuaJIT and my program are both compiled with GCC 4.7.2 on Windows. I'm
using LuaJIT 2.0.2.

Thank you for any insight!

Other related posts: