Lua使用C ++段错误共享对象加载

时间:2014-07-03 14:29:37

标签: c++ lua

对于我正在编写的项目,我需要编写一个自定义的Lua模块加载系统,我之前已经在我的Raspberry Pi上完成了它,但不是在我的Mac上。问题是,只要我尝试访问共享对象中的lua_State,程序会出现段错误。

main.cpp

#include <lua.hpp>
#include <dlfcn.h>
#include <iostream>

typedef void Register(lua_State*);

int main(){
    lua_State* L = luaL_newstate();
    void* lib = dlopen("module.so", RTLD_NOW);
    if(!lib){
        std::cerr << "Error opening module \""  << "\": " << dlerror() << std::endl;
        return;
    }
    Register* loadFunc = (Register*)dlsym(lib, "RegisterModule");
    if(!loadFunc){
        std::cerr << "Error loading symbols from module \""  << "\": " << dlerror() << std::endl;
        return;
    }
    loadFunc(L);
    for(;;){}


    return 1;
}

module.cpp

#include <lua.hpp>
#include <iostream>

static int Foo(lua_State* L){
    std::cout << "Hello World!" << std::endl;
}

extern "C" void RegisterModule(lua_State* L){
    lua_pushcfunction(L, Foo);
    lua_setglobal(L, "Foo");
}

Makefile

lua = -L /usr/lib/lua5.2 -I /usr/include/lua5.2 -llua
luaHeaders = -I /usr/include/lua5.2

all: main module.so
    rm -f main.o

main: main.o
    clang++ main.o -o main $(lua) -ldl

main.o: main.cpp
    clang++ -c main.cpp $(luaHeaders)

module.so: module.cpp
    clang++ -fPIC -shared module.cpp -o module.so $(lua)

我的设置是:

  • Mac OS X 10.9 Mavericks和Elementary OS Luna
  • Lua 5.2

调试器(lldb)的输出

Process 19943 stopped
* thread #2: tid = 0x23ec1c, 0x0000000100295c31 myModule.so`luaH_newkey + 913, stop reason = EXC_BAD_ACCESS (code=2, address=0x100073db0)
    frame #0: 0x0000000100295c31 myModule.so`luaH_newkey + 913
myModule.so`luaH_newkey + 913:
-> 0x100295c31:  movq   %rax, 16(%r12)
   0x100295c36:  movl   8(%rbx), %eax
   0x100295c39:  movl   %eax, 24(%r12)
   0x100295c3e:  testb  $64, 8(%rbx)

0 个答案:

没有答案