代码之家  ›  专栏  ›  技术社区  ›  Overv

使用LuabDin将C++类导出到Lua时的访问冲突

  •  1
  • Overv  · 技术社区  · 15 年前

    我试图使用luabind将一个简单类导出到lua。我从两个网站获取的代码显示了大致相同的方法,但仍然失败。

    // Default headers
    #include <iostream>
    #include <string>
    
    // Lua headers
    extern "C" {
        #include "lua.h"
        #include "lualib.h"
        #include "lauxlib.h"
    }
    
    #include "luabind/luabind.hpp"
    
    // Sample class
    class NumberPrinter
    {
    public:
        NumberPrinter( int number ) : m_number( number ) {}
        void print() { std::cout << m_number << "\n"; }
    
    private:
        int m_number;
    };
    
    int main() {
        // Create Lua state and load sample file
        lua_State *luaState = lua_open();
        luabind::open( luaState );
    
        // Set up bind to number class
        luabind::module( luaState ) [
            luabind::class_<NumberPrinter>( "NumberPrinter" )
                .def( luabind::constructor<int>() )
                .def( "print", &NumberPrinter::print )
        ];
    
        // Use the class in Lua
        luaL_dostring( luaState,
            "Print2000 = NumberPrinter(2000)\n"
            "Print2000:print()\n"
        );
    
        // Clean up Lua state
        lua_close( luaState );
    
        getchar();
        return 0;
    }
    

    运行该代码时,luabind::module会导致以下运行时错误,并且在调试模式下没有其他信息:

    中0x690008f5处的未处理异常 lua playground.exe:0xc000005:访问 违反。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Hans Passant    15 年前

    我鼓励您从二进制文件开始,并从 this website . 它与您试图运行的示例代码完全相同(减去输入错误),并且在我的机器上运行良好。如果仍然不起作用,你需要lua社区的帮助。可能需要一个小型转储来帮助他们诊断,只是异常消息不够。