Re: LuaJIT C++ API with templates advice

  • From: Daniel Thompson <danothom10@xxxxxxxxxxx>
  • To: "luajit@xxxxxxxxxxxxx" <luajit@xxxxxxxxxxxxx>
  • Date: Tue, 27 Aug 2013 15:00:21 +0100 (BST)

Hi Steve,

Not that much too it really. I think I was trying to be over complicated in my 
initial approach.

Solved it by simply passing out a ffi.cast("void* , derived_ptr) as the 
parameter to the C++ function which is expecting a Base*. The FFI automagically 
does the necessary void* -> Base* conversion, and then the transitive 
properties of upcasting a derived pointer to its base while passed as a 
function argument resolves everything correctly. So I don't need explicit 
casting or anything else like that on the C++ side of things. Which allows me 
to use the function in a more flexible manner.

Example :

--*** C++
extern "C" __declspec(dllexport) void addFoo(Base* c) {
c->doSomethingWithDerivedObjectWithoutCasting();  // implicitly casted
}
--***

--*** Lua
ffi = require 'ffi'
ffi.cdef[[
typedef struct Base Base;

typedef struct DerivedDerived;
void  addFoo(Base* c);
]]

local derived_ptr = ffi.new("Derived")
ffi.C.addFoo(ffi.cast("void *", derived_ptr))
--***

NOTE: my Base class is virtual and I'm not passing the Derived object by value 
to prevent object slicing and all that jazz.

I guess I probably don't need the void * and could just cast the Derived* to 
the Base* instead. Is there any benefit to casting to void* as apposed to the 
Base*?

Something which has also helped me a bunch is figuring how to still use 
namespaces and extern "C" on #include "headerWithLuaExportedFunctions.h" 
statements in source files.

So... nothing magical as I'm still a C++ noob at the end of the day. But 
anyway, it works for me which is nice as it means I can still use C++ 
inheritance and some of those benefits etc.


________________________________
 From: steve donovan <steve.j.donovan@xxxxxxxxx>
To: luajit@xxxxxxxxxxxxx 
Sent: Tuesday, 27 August 2013, 10:44
Subject: Re: LuaJIT C++ API with templates advice
 

On Tue, Aug 27, 2013 at 11:02 AM, Daniel Thompson
<danothom10@xxxxxxxxxxx> wrote:
> Nevermind, figured it out :)

Do tell us how you did it - I'm also curious to know how FFI interacts
with C++.  When I was messing around with a C++ interpreter, the
second hardest thing was coping with loading external C++ shared
libraries and the weird (and always changing) C++ ABI. (Mangling was
_not_ the difficult bit)

Other related posts: