c++ - 帮助提升绑定(bind)/功能

标签 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...时,还是报错转换问题

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

有人知道怎么解决吗?

最佳答案

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

关于c++ - 帮助提升绑定(bind)/功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1413744/

相关文章:

loops - 如何在 Lua 中的二维表上创建迭代器?

java : Function objects as strategies

c++ - 如何在 C++ 中定义接受派生类成员函数指针作为参数的类方法?

c++ - 如何使用 Gmock 连续调用第 n 次返回特定值

c++ - 在 STL 映射中,使用 map::insert 比使用 [] 更好吗?

java - 在Java中嵌入Lua函数作为成员变量

c++ - C++ 中的函数指针转换

c++ - 用递归函数实现 neper number (e)

c++ - OSX "error: cannot convert ' const std::__cxx11::basic_string<char>"是什么意思?

macos - 无法在主目录中使用 io.open - Lua