gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:12:05 25 4
gpt4 key购买 nike

我正在使用 lua 扩展一个接口(interface),但我遇到了一个问题,我需要将指向对象的指针传递给要处理的 lua 代码。这些类将通过 SWIG 包装,我可以使用 swig 通过 lua 实例化它们,但这会让我留下无用的对象。

我需要能够将回调对象传递给 lua,以及代表事件的对象。我不能手动将回调定义为全局回调,因为那样会引入 Not Acceptable 约束。

所以对于一个通用的例子,给定一个类 C 和 lua 中的一个函数,它接受 1 个参数,我如何在将 C 类型的 C++ 指针传递给它的同时调用该 lua 函数?

最佳答案

啊哈,回答我自己的问题,但我找到了!

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. Swig is really good for just wrappering up a C/C++ library to get it readable by lua. Getting the C++ to talk to lua is fairly easy, but not well documented.

You idea of lua_pushlightuserdata(), was close, but not there. 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. The last param (in this case 1) is whether you want lua to manage the memory (0 for no, 1 for yes).

The SWIG_NewPointerObj() and SWIGTYPE_p_Foo are both found in the wrapping file.

Once you have that you should be able to do in lua:

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

Let me know if you have any other questions. Regards, Mark

关于c++ - 将非全局 C++ 对象传递给 Lua 函数 (Swig),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2395501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com