Lua调用c++对象出现的问题,大神请进 ,高分相送

advancedchan 2014-03-20 05:12:32
首先说明下Lua中调用一个c++的类的实例指针,这个指针是C++传入到Lua中,第一个参数是数字,第二个是指针,第一个数字在LUA中都是对的,在第二个参数指针p就不对了,LUA中打印出地址和C++显示的地址不一样,
在调用p:init()就报错说attempt to index local 'p' (a userdata value)
怎么解决啊?
...全文
428 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
advancedchan 2014-03-21
  • 打赏
  • 举报
回复
//注册类 static void Register(lua_State* L, const char* name, bool gc = false) { tname = name; manageMemory = gc; lua_settop(L, 0); // clean stack lua_newtable(L); int methods = lua_gettop(L); luaL_newmetatable(L, tname); int metatable = lua_gettop(L); // store method table in globals so that // scripts can add functions in Lua lua_pushvalue(L, methods); lua_setglobal(L, tname); // hide metatable lua_pushvalue(L, methods); lua_setfield(L, metatable, "__metatable"); lua_pushvalue(L, methods); lua_setfield(L, metatable, "__index"); lua_pushcfunction(L, tostringT); lua_setfield(L, metatable, "__tostring"); lua_pushcfunction(L, gcT); lua_setfield(L, metatable, "__gc"); lua_newtable(L); lua_setmetatable(L, methods); } //绑定函数 template<typename C> static void SetMethods(lua_State* L, ElunaRegister<C>* methodTable) { if (!methodTable) return; if (!lua_istable(L, 1)) return; lua_pushstring(L, "GetObjectType"); lua_pushcclosure(L, type, 0); lua_settable(L, 1); for (; methodTable->name; ++methodTable) { lua_pushstring(L, methodTable->name); lua_pushlightuserdata(L, (void*)methodTable); lua_pushcclosure(L, thunk, 1); lua_settable(L, 1); } } //绑定对象 static int push(lua_State* L, T const* obj) { if (!obj) { lua_pushnil(L); return lua_gettop(L); } luaL_getmetatable(L, tname); if (lua_isnoneornil(L, -1)) return luaL_error(L, "%s missing metatable", tname); T const** ptrHold = (T const**)lua_newuserdata(L, sizeof(T**)); if (ptrHold) { *ptrHold = obj; lua_pushvalue(L, -2); lua_setmetatable(L, -2); } lua_replace(L, -2); return lua_gettop(L); }
advancedchan 2014-03-21
  • 打赏
  • 举报
回复
p = 0x031957a8 {m_socket=1000 m_bIsNewbie=false m_isDel=false ...}这是在C++中看到的地址,下面是在lua中print(p)输出的
advancedchan 2014-03-20
  • 打赏
  • 举报
回复
我是做了封装绑定得,要看源码加我QQ:64409324,不想把代码贴在这里
sniffer12345 2014-03-20
  • 打赏
  • 举报
回复
引用 楼主 advancedchan 的回复:
首先说明下Lua中调用一个c++的类的实例指针,这个指针是C++传入到Lua中,第一个参数是数字,第二个是指针,第一个数字在LUA中都是对的,在第二个参数指针p就不对了,LUA中打印出地址和C++显示的地址不一样, 在调用p:init()就报错说attempt to index local 'p' (a userdata value) 怎么解决啊?
汗。。谁跟你说传指针给lua就能直接用啦?要真那样那得省多少功夫。 老老实实用tolua++之类的去绑定吧,要不就写C接口封装c++。
勤奋的小游侠 2014-03-20
  • 打赏
  • 举报
回复
虽然不知道你在lua中是怎么实现这个类的,但你直接在c++中传一个指针给lua,似乎不太对吧?把你类的构造函数和lua代码贴上来看看?
advancedchan 2014-03-20
  • 打赏
  • 举报
回复
print(p)输出就是地址,但不C++里地址不是指向同一个地址,稍有偏移
alga_1 2014-03-20
  • 打赏
  • 举报
回复
先print(p),看看p到底是个什么东东
advancedchan 2014-03-20
  • 打赏
  • 举报
回复
没有人顶自己顶一下

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧