Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get C++ "this" address from registered instances in Lua back to C++? #148

Open
shohnwal opened this issue Mar 17, 2016 · 0 comments

Comments

@shohnwal
Copy link

Lets say i have a C++ Luainterface class instance that i want to register in Lua:
When registering an already created C++ class instance ina Lua via

void Luainterface::registerMyself() {
    this->lua["CPPinterface"].SetObj(
        *this,
        "cpp_dosomething", &Luainterface::cpp_dosometing
        );
}

and working with the object in Lua and i want to pass the class instances address (or pointer) back to C++ so i can access the instace via a converted C++ pointer, how would i do that?

To be more exact, how do i access the "*this" element in the (in this example) CPPinterface table so i can pass this address back to C++ and work with it?
The other elements (like &Luainterface::cpp_print) are all associated with a string and it's easy to access them, but i can't figure out how to access the "*this" element containing the objects address.

So far i've been creating extra class member with a pointer on itself

class Luainterface {
Luainterface() : cpp_thispointer(this) {} //constructor
//other stuff
Luainterface* cpp_thispointer; //class instance member pointing on itself
}

and register it in the SetObj function in addition to the rest

void Luainterface::registerMyself() {
    this->lua["CPPinterface"].SetObj(
        *this,
        "cpp_this", &Luainterface::cpp_thispointer,
        "cpp_dosomething", &Luainterface::cpp_dosometing
        );
}

It works by converting the Lua table element in C++ back to its originaltype

Luainterface* pointer = (Luainterface*)lua["CPPinterface"]["cpp_this"]()

but it's a bit cumbersome to have that extra member element and extra lua function to register and remember.
Would it be somehow possible to access the "*this" element (used during the objects registration itself as seen in the example above) in Lua so i can send it back to C++ and convert it back to a pointer or address? Or does the "*this" element used above not end up in the Lua table at all and we have to do something like extra entries/members, like i have done above?

PS: Thank you for creating Selene, it's quite awesome! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant