如何在多线程应用程序中允许C模块访问Lua状态?

时间:2018-07-05 01:44:34

标签: c++ c multithreading lua

我有另一个开发人员开发的大型 C / C ++ / Lua 多线程应用程序。我没有消息来源。 应用具有内置的自定义 Lua (无Lua.dll)。我只能通过Lua API(确切地说是Avorion Lua API)与之交互。

我有一个用{strong> C 编写的Lua模块的源代码,并且我需要将其编译成.so/.dll并使其工作。 / p>

问题是,当我尝试使用requirepackage.loadlib进行加载时,应用崩溃并显示 Access violation 错误。我用Google搜索了它,似乎它与线程相关。

所以我正在寻求一种解决此问题的方法。我应该在 C 模块代码中进行编辑还是在Lua端执行某些操作?

UPD:我知道 C 模块具有正确的代码,它可以在 Lua 单线程解释器中完美运行。

我的C模块(与Lua 5.2.4 .lib编译):

#if defined(WIN32) || defined(_WIN32)
#  define LUA_BUILD_AS_DLL   /* for #define LUA_API __declspec(dllimport) */
#endif

#ifdef __cplusplus
extern "C" {
#endif

#include <lua.h>
#include <lauxlib.h>

#ifdef __cplusplus
}
#endif

#if defined(WIN32) || defined(_WIN32)
#  ifdef __cplusplus
#    define LUA_LIB   extern "C" __declspec(dllexport)
#  else
#    define LUA_LIB   __declspec(dllexport)
#  endif
#else
#  define LUA_LIB     extern "C"
#endif


static int Lmytest_test(lua_State *L) {
    // Check the arguments.
    int argn = lua_gettop(L);
    if (argn != 1 || !lua_isstring(L, 1)) {
        lua_pushstring(L, "Give me one string argument please!");
        lua_error(L);
    }
    lua_pushstring(L, "Hello world!");
    return 2;
}

LUA_LIB int luaopen_mytest(lua_State* L) {
    luaL_Reg lib[] = {
#define ENTRY(name) { #name, Lmytest_##name }
        ENTRY(test),
#undef  ENTRY
        { NULL, NULL }
    };

#if LUA_VERSION_NUM >= 502
    luaL_newlib(L, lib);
#else
    lua_createtable(L, 0, sizeof(lib) / sizeof(lib[0]));
    luaL_register(L, NULL, lib);
#endif

    return 1;
}

我正在通过文件顶部的Lua代码来请求它:

local mytest = package.loadlib("data/scripts/lib/mytest.dll", "luaopen_mytest")()
print(mytest.test("Test"))

1 个答案:

答案 0 :(得分:0)

尝试暂时将其设为C代码

#if defined(WIN32) || defined(_WIN32)
#  define LUA_BUILD_AS_DLL   /* for #define LUA_API __declspec(dllimport) */
#endif

#ifdef __cplusplus
extern "C" {
#endif

#include <lua.h>
#include <lauxlib.h>

#ifdef __cplusplus
}
#endif

#if defined(WIN32) || defined(_WIN32)
#  ifdef __cplusplus
#    define LUA_LIB   extern "C" __declspec(dllexport)
#  else
#    define LUA_LIB   __declspec(dllexport)
#  endif
#else
#  define LUA_LIB     extern "C"
#endif

然后放置lua代码的第二行,因此它仅加载上面的代码。