简体   繁体   English

将非全局C ++对象传递给Lua函数(Swig)

[英]Passing non-Global C++ objects to Lua functions (Swig)

I am extending an interface with lua, and I've run into a problem in that I would need to pass pointers to objects to the lua code to work upon. 我正在扩展与lua的接口,但遇到一个问题,我需要将指向对象的指针传递给lua代码以进行处理。 These classes will have been wrapped via SWIG, and I could instantiate them via lua using swig, but that would leave me with useless objects. 这些类将通过SWIG进行包装,我可以使用swig通过lua实例化它们,但这将给我留下无用的对象。

I need to be able to pass a callback object to lua, as well as objects representing things on events. 我需要能够将回调对象以及表示事件中对象的对象传递给lua。 I cannot manually define the callback as global because that would introduce a constraint which is unnacceptable. 我无法将回调手动定义为全局回调,因为这会引入无法接受的约束。

So for a generic example, given a class C and a function in lua that takes 1 parameter, how do I call that lua function while passing it the C++ pointer of type C? 因此,对于一个通用示例,给定C类和lua中具有1个参数的函数,我如何在将该lua函数传递给C类型的C ++指针时调用它?

Aha, answering my own question, but I founds it! 啊哈,回答了我自己的问题,但是我发现了!

http://lua-users.org/lists/lua-l/2007-05/msg00053.html http://lua-users.org/lists/lua-l/2007-05/msg00053.html

Hello Joey, 你好乔伊,

I do almost all my SWIG-LUA work from the lua side. 我几乎从lua方面完成所有SWIG-LUA工作。 Swig is really good for just wrappering up a C/C++ library to get it readable by lua. Swig非常适合仅包装一个C / C ++库以使其被lua读取。 Getting the C++ to talk to lua is fairly easy, but not well documented. 让C ++与lua对话非常容易,但是没有充分的文档记录。

You idea of lua_pushlightuserdata( ), was close, but not there. 您对lua_pushlightuserdata( )的想法很接近,但是还不存在。 You probably want something like this: 您可能想要这样的东西:

 Foo* p= new Foo(); SWIG_NewPointerObj(L,p,SWIGTYPE_p_Foo,1); lua_setglobal (L, "p"); 

The SWIG_NewPointerObj() creates a userdata (not a lightuserdata) for the foo object & pushes it to the stack. SWIG_NewPointerObj()为foo对象创建一个用户数据(不是lightuserdata)并将其压入堆栈。 The last param (in this case 1) is whether you want lua to manage the memory (0 for no, 1 for yes). 最后一个参数(在本例中为1)是您是否要lua管理内存(0表示否,1表示是)。

The SWIG_NewPointerObj() and SWIGTYPE_p_Foo are both found in the wrapping file. 在包装文件中都可以找到SWIG_NewPointerObj()SWIGTYPE_p_Foo

Once you have that you should be able to do in lua: 一旦有了,您应该可以在lua中进行操作:

 print(p) print(swig_type(p)) p:some_function() 

Let me know if you have any other questions. 如果您还有其他问题,请告诉我。 Regards, Mark 问候,马克

I haven't used Swig with C++ and Lua, but you can do it without Swig in two different ways (userdata and closures). 我没有将Swig与C ++和Lua一起使用,但是您可以在没有Swig的情况下以两种不同的方式(用户数据和闭包)进行操作。 I don't know if Swig interferes somehow with this. 我不知道Swig是否以此干扰。

Using Userdata 使用用户数据

lua_pushcclosure lua_pushcclosure

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM