- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在我的 c++ 游戏项目中使用 lua 5.1,但是当我尝试注册一个 c++ 成员函数时,我无法使用 lua。我想在 lua 中使用我的 c++ 类成员函数,但是 lua_register() 函数的第 3 个参数只能接受c类型的普通函数指针或静态成员函数的指针。
听说lua bind库可以解决这个问题,但是我不想用lua bind。这很好,但对我的项目来说太重了。有没有什么方法可以在没有任何库的情况下注册 C++ 成员函数?我该怎么办?
最佳答案
我自己也有过同样的经历。
我知道基本上有两个很好的解决方案。如果成员函数是针对每个 lua 状态只有一个的类,则一个很好。另一个更灵活但更复杂且更慢。 (我很想学习其他方法/这些方法的改进!)
我认为 lua_bind 使用一些与方法 1 非常相似的模板,但使用技巧使实现与方法 2 一样灵活。我认为这两种方法都比 lua_bind 更透明。
(1) my_class
的每个成员函数,你想传递给lua,它应该接受lua_State * L
并返回int
.
(2) 在lua初始化的时候,在lua_extraspace
中存储一个指向关联的my_class
的指针。
*static_cast<my_class**>(lua_getextraspace(L_)) = &instance;
(3) 当你想把成员函数传递给lua时,使用这样的模板:
typedef int (my_class::*mem_func)(lua_State * L);
// This template wraps a member function into a C-style "free" function compatible with lua.
template <mem_func func>
int dispatch(lua_State * L) {
my_class * ptr = *static_cast<my_class**>(lua_getextraspace(L));
return ((*ptr).*func)(L);
}
然后你注册这样的东西:
const luaL_Reg regs[] = {
{ "callback_1", &dispatch<&my_class::callback_1> },
{ "callback_2", &dispatch<&my_class::callback_2> },
{ "callback_3", &dispatch<&my_class::callback_3> },
{ NULL, NULL }
};
luaL_register(L, regs);
方法一的好处是比较简单,而且速度极快,我觉得会比lua bind快。因为,get_extraspace
除了一点指针运算外什么都不做。最有可能的是,一个好的编译器可以优化 dispatch
模板,以便它生成的函数是内联的,并且不会有任何开销。
您可能想要更改 dispatch
模板,以便在额外空间进行空指针检查,这取决于您的 lua 状态和 my_class
的生命周期得到管理。
潜在地,您还可以在额外空间中存储更复杂的东西,例如指向多个不同对象的指针,甚至像 vector 或其他东西(您可以在他们的文档中阅读有关如何配置 lua 额外空间的信息)。或者您可以将内容存储在 lua 注册表中,调度函数可以从那里检索它们,但是额外空间更快——这取决于您。
在方法 2 中,您基本上使用通常的 lua 技术将 C++ 对象推送到 lua 拥有的 lua,但是您在对象是 C++ std::function
的地方执行此操作,并且您重载 _call
元函数,以便它调用该函数。 (如果您不使用 C++11,则可以使用 boost::function
。)
然后当你想把一个c++的成员函数推送给lua时,你可以使用std::bind
让它成为一个函数对象。
这个方法有一个缺点,在 lua 中,“函数”的类型实际上是 userdata
,但是因为你可以很好地调用它并将它用作一个函数,所以它实际上并不是事情。如果这对你不利,你可以做的一件事是使用相同的技巧,但之后,创建一个将函数对象 userdata 作为上值的闭包,当调用闭包时,它只是将参数转发给函数对象并返回结果。然后闭包的类型在 lua 中将是 function
,但它会做基本相同的事情。
typedef std::function<int(lua_State *)> lua_function;
char const * cpp_function = "CPP_Function";
static int intf_dispatcher ( lua_State* L )
{
//make a temporary copy, in case lua_remove(L,1) might cause lua to garbage collect and destroy it
lua_function f = * static_cast<lua_function *> (luaL_checkudata(L, 1, cpp_function));
// remove from the stack before executing, so that like all other callbacks, f finds only its intended arguments on the stack.
lua_remove(L,1);
int result = (f)(L);
return result;
}
static int intf_cleanup ( lua_State* L )
{
lua_function * d = static_cast< lua_function *> (luaL_testudata(L, 1, cpp_function));
if (d == NULL) {
std::cerr << "ERROR: intf_cleanup called on data of type: " << lua_typename( L, lua_type( L, 1 ) ) << std::endl;
lua_pushstring(L, "C++ function object garbage collection failure");
lua_error(L);
} else {
d->~lua_function();
}
return 0;
}
static int intf_tostring( lua_State* L )
{
lua_function * d = static_cast< lua_function *> (luaL_checkudata(L, 1, cpp_function));
// d is not null, if it was null then checkudata raised a lua error and a longjump was executed.
std::stringstream result;
result << "c++ function: " << std::hex << d;
lua_pushstring(L, result.str().c_str());
return 1;
}
void register_metatable ( lua_State* L )
{
luaL_newmetatable(L, cpp_function);
lua_pushcfunction(L, intf_dispatcher);
lua_setfield(L, -2, "__call");
lua_pushcfunction(L, intf_cleanup);
lua_setfield(L, -2, "__gc");
lua_pushcfunction(L, intf_tostring);
lua_setfield(L, -2, "__tostring");
lua_pushvalue(L, -1); //make a copy of this table, set it to be its own __index table
lua_setfield(L, -2, "__index");
lua_pop(L, 1);
}
void push_function( lua_State* L, const lua_function & f )
{
void * p = lua_newuserdata(L, sizeof(lua_function));
luaL_setmetatable(L, cpp_function);
new (p) lua_function(f);
}
关于c++ - c++ - 如何在没有lua绑定(bind)的情况下将成员函数注册到lua,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32416388/
我是 Java 新手,这是我的代码, if( a.name == b.name && a.displayname == b.displayname && a.linknam
在下面的场景中,我有一个 bool 值。根据结果,我调用完全相同的函数,唯一的区别是参数的数量。 var myBoolean = ... if (myBoolean) { retrieve
我是一名研究 C++ 的 C 开发人员: 我是否正确理解如果我抛出异常然后堆栈将展开直到找到第一个异常处理程序?是否可以在不展开的情况下在任何 throw 上打开调试器(即不离开声明它的范围或任何更高
在修复庞大代码库中的错误时,我观察到一个奇怪的情况,其中引用的动态类型从原始 Derived 类型更改为 Base 类型!我提供了最少的代码来解释问题: struct Base { // some
我正在尝试用 C# 扩展给定的代码,但由于缺乏编程经验,我有点陷入困境。 使用 Visual Studio 社区,我尝试通过控制台读出 CPU 核心温度。该代码使用开关/外壳来查找传感器的特定名称(即
这可能是一个哲学问题。 假设您正在向页面发出 AJAX 请求(这是使用 Prototype): new Ajax.Request('target.asp', { method:"post", pa
我有以下 HTML 代码,我无法在所有浏览器中正常工作: 我试图在移动到
我对 Swift 很陌生。我如何从 addPin 函数中检索注释并能够在我的 addLocation 操作 (buttonPressed) 中使用它。我正在尝试使用压力触摸在 map 上添加图钉,在两
我设置了一个详细 View ,我是否有几个 Nib 文件根据在 Root View Controller 的表中选择的项目来加载。 我发现,对于 Nibs 的类,永远不会调用 viewDidUnloa
我需要动态访问 json 文件并使用以下代码。在本例中,“bpicsel”和“temp”是变量。最终结果类似于“data[0].extit1” var title="data["+bpicsel+"]
我需要使用第三方 WCF 服务。我已经在我的证书存储中配置了所需的证书,但是在调用 WCF 服务时出现以下异常。 向 https://XXXX.com/AHSharedServices/Custome
在几个 SO 答案(1、2)中,建议如果存在冲突则不应触发 INSERT 触发器,ON CONFLICT DO NOTHING 在触发语句中。也许我理解错了,但在我的实验中似乎并非如此。 这是我的 S
如果进行修改,则会给出org.hibernate.NonUniqueObjectException。在我的 BidderBO 类(class)中 @Override @Transactional(pr
我使用 indexOf() 方法来精细地查找数组中的对象。 直到此刻我查了一些资料,发现代码应该无法正常工作。 我在reducer中尝试了上面的代码,它成功了 let tmp = state.find
假设我有以下表格: CREATE TABLE Game ( GameID INT UNSIGNED NOT NULL, GameType TINYINT UNSIGNED NOT NU
代码: Alamofire.request(URL(string: imageUrl)!).downloadProgress(closure: { (progress) in
我是一名优秀的程序员,十分优秀!