zzy
zzy

Reputation: 1793

How could I let lua take ownership of return value when using tolua++?

Here is my C++ code:

// tolua_begin
const char* GetSomeString() {
    std::string result;
    // do something
    return result.c_str();
}
// tolua_end

I know when the function return, result will be freed and lua will get nothing if I call it in lua. I need new one to forbidden it be freed. But it will cause memory leak. So I should let lua take ownership of the return value.

I know how to do this using lua_State. But I'm using comment to expose my c++ functions to lua, so I'm wondering whether there is a similar way to achieve it?

Upvotes: 2

Views: 93

Answers (1)

Tamás Szelei
Tamás Szelei

Reputation: 23941

This has nothing to do with your lua binding. When you return from the function, the result string is destructed and the pointer that points to its internal buffer will point to freed memory. There is no point in time when the library has a chance of taking ownership of this string, because ultimately it just performs a function call and the result is only available after the function has returned (by which time it's unusable). After a cursory google search, I think tolua++ supports std::string return values, so you could do this:

// tolua_begin
std::string GetSomeString() {
    std::string result;
    // do something
    return result;
}
// tolua_end

This will work because the string is copied.

Upvotes: 3

Related Questions