帮助使用Boost库的bind/函数。

我必须匹配以下的函数签名:

typedef int (*lua_CFunction) (lua_State *L);//target sig

这是我目前的代码:

    //somewhere else...
    ...
registerFunction<LuaEngine>("testFunc", &LuaEngine::testFunc, this);
    ...

    //0 arg callback
void funcCallback0(boost::function<void ()> func, lua_State *state)
{
    func();
}

template<typename SelfType>
void registerFunction(const std::string &funcName, boost::function<void (SelfType*)> func, SelfType *self)
{
            //funcToCall has to match lua_CFunction
    boost::function<void (lua_State *)> funcToCall = boost::bind(&LuaEngine::funcCallback0, this,
        boost::bind(func, self), _1);
    lua_register(_luaState, funcName.c_str(), funcToCall);
}

不过,在 lua_register(_luaState... 这里,它仍然抱怨转换问题。

Error 1 error C2664: 'lua_pushcclosure' : cannot convert parameter 2 from 'boost::function' to 'lua_CFunction'

有人知道如何解决这个问题吗?

原文链接 https://stackoverflow.com/questions/1413744

点赞
stackoverflow用户45262
stackoverflow用户45262

问题在于编译器不能推断模板参数,因为存在隐式转换。

您需要将函数指针存储到一个函数对象中。

function<int(lua_State *)> f = boost::bind(&LuaEngine::testFunc, this)
registerFunction<LuaEngine>("testFunc", f);

而且,您的函数期望返回类型为 void,必须更改为 int。

2009-09-11 23:54:26
stackoverflow用户111335
stackoverflow用户111335

这个问题不能直接解决。Lua API需要你提供一个普通的函数指针-这只是一个代码指针,没有其他东西。同时,boost::function是一个函数对象,不可能转换为普通的函数指针,因为它捕获的不仅仅是代码,还有状态。在你的例子中,捕获的状态是self的值。因此它有一个代表代码的指针和一些数据-而目标API仅期望代码指针。

2009-09-12 00:15:24