gpt4 book ai didi

函数指针的 C++ lua 桥接问题

转载 作者:行者123 更新时间:2023-11-30 04:19:23 30 4
gpt4 key购买 nike

我正在尝试在 *lua_CFunction* 上创建一个简单的 C++ 包装器,它的定义如下:

// header
typedef int (*lua_CFunction) (lua_State* lua);
...
lua_CFunction wrap (std::function <int (Game* game)> function);
// implementation
lua_CFunction ScriptingInterface::wrap (std::function <int (Game* game)> function)
{
return [this, function] (lua_State* unused) -> int {
int n_args = function (this->game);
return n_args;
};
}
void ScriptingInterface::registerFunction (std::string name, std::function <int (Game* game)> function)
{
lua_register (lua, name.c_str (), wrap (function));
}

想法是创建这样的公共(public)函数:

int setTitle (Game* interface) 
{
const char* title = lua_tostring (interface->getScripts ()->getLuaState (), 1);

SDL_WM_SetCaption (title, NULL);

return 0;
}

然后像 lua 一样分享它们:

scripts->registerFunction ("setTitle", setTitle);

scriptsScriptingInterface

的实例

尝试编译游戏时出现问题。

./scripting/scripting_interface.cc: In member function ‘int (* ScriptingInterface::wrap(std::function<int(Game*)>))(lua_State*)’:
./scripting/scripting_interface.cc:40:2: error: cannot convert ‘ScriptingInterface::wrap(std::function<int(Game*)>)::<lambda(lua_State*)>’ to ‘int (*)(lua_State*)’ in return
./scripting/scripting_interface.cc:41:1: warning: control reaches end of non-void function [-Wreturn-type]

谁能告诉我我在这里做错了什么,因为据我所知代码应该可以毫无问题地编译?

最佳答案

问题出在这里:

lua_CFunction ScriptingInterface::wrap(std::function<int(Game*)> function) 
{
return [this, function] (lua_State* unused) -> int {
int n_args = function (this->game);
return n_args;
};
}

您正试图在需要函数指针的地方返回一个 lambda,但是 捕获 lambda 无法转换为函数指针 - 而您的 lambda 正在同时捕获 thisfunction .根据 C++11 标准的第 5.1.2/6 段:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

不幸的是,除非你能返回一个 std::function<int(lua_State*)> ,您将不得不更改设计。

关于函数指针的 C++ lua 桥接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15861168/

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