2

This is what I did. I created a struct and a static function in my C++ code

struct ItemDefinition {
  int64_t price;
};
int static getPrice(lua_State* L) {

  ItemDefinition* def = (ItemDefinition*)lua_touserdata(L, 1);
  printf("%p\n", def);
  printf("%d\n", def->price);
  return 0;
}

I also registered the function in lua and initialized an ItemDefination object.

ItemDefinition def;
def.price = 120;
lua_pushlightuserdata(lua_state_, (ItemDefinition*)&def);
lua_setglobal(lua_state_, "def");
luaL_Reg module[] = {{"getPrice", &getPrice}, {NULL, NULL}};

from my Lua script, I just simply call the function

getPrice(def)

if works fine if I just print out the def's address. So I'm sure the function get called successfully. However, if I'm trying to get def->price, I will get an error from address sanitizer "==283789==ERROR stack use after return" I'm not familiar with both and . Could you please help where the problem could be?

user2736738
  • 30,591
  • 5
  • 42
  • 56
Chris
  • 21
  • 2
  • The format specifier `%d` is incorrect for the type `int64_t`. – Weather Vane Mar 02 '18 at 18:59
  • BTW, I'm trying to create a global object, the "def" in my example and it will be called for many times.. So the test actually call the getPrice method many times. I'm not sure if this behavior causes the problem? – Chris Mar 02 '18 at 19:01
  • 1
    Please [see this](https://stackoverflow.com/questions/9225567/how-to-print-a-int64-t-type-in-c/9225648). – Weather Vane Mar 02 '18 at 19:02

1 Answers1

0

Resolve the issue, NVM. It's actually because the pointer issue.

Chris
  • 21
  • 2