帮助提升绑定/功能

时间:2009-09-11 23:38:20

标签: c++ lua function-pointers boost-bind boost-function

我有这个功能签名我必须匹配

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...,它仍在抱怨转化问题

  

错误1错误C2664:   'lua_pushcclosure':无法转换   参数2来自   'boost :: function'来   'lua_CFunction'

任何人都知道如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

这不能直接解决。 Lua API想要一个普通的函数指针 - 这只是一个代码指针,而不是别的。同时,boost::function是一个函数对象,并且它无法转换为普通函数指针,因为 - 粗略地说 - 它不仅捕获代码,还捕获状态。在您的示例中,捕获的状态是self的值。所以它有代码的代码指针和一些数据 - 而目标API只需要代码指针。

答案 1 :(得分:1)

问题是编译器无法推断模板参数,因为存在隐式转换。

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

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

你的函数需要一个void返回类型,并且需要更改为int。