如何创建 Lua 模块的 dll

我正在尝试编写一个外部 Lua 模块。

我使用 Windows 8.1,并使用 gcc 作为编译器。

我的要求是自己构建/编译所有东西,而不使用在线可用的预编译文件。

首先,我按照以下方式构建 Lua 5.2.4 的 C 源代码:

  1. gcc -c *.c

  2. ren lua.o lua.obj

  3. ren luac.o luac.obj

  4. ar rcs luaX.X.X.lib *.o

  5. gcc -shared -o luaX.X.X.dll *.o

  6. gcc lua.c luaX.X.X.lib -o luaX.X.X.exe

  7. gcc luac.c luaX.X.X.lib -o luacX.X.X.exe

  8. del *.o *.obj

这里的 X.X.X 是源代码的版本号。

一旦我创建了我的 .exe,我编写了我的模块的 C 代码(让我们称其为 LuaMath):

#include<windows.h>
#include<math.h>
#include "lauxlib.h"
#include "lua.h"

static int IdentityMatrix(lua_State *L)
{
    int in = lua_gettop(L);
    if (in!=1)
    {
       lua_pushstring(L,"最多只有 1 个参数");
       lua_error(L);
    }
    lua_Number n = lua_tonumber(L,1);
    lua_newtable(L);                  /*                 tabOUT n */
    int i,j;
    for (i=1;i<=n;i++)
    {
        lua_newtable(L);              /*         行(i) tabOUT n */
        lua_pushnumber(L,i);          /*       i 行(i) tabOUT n */
        for (j=1;j<=n;j++)
        {
            lua_pushnumber(L,j);      /*     j i 行(i) tabOUT n */
            if (j==i)
            {
                lua_pushnumber(L,1);
            }
            else                      /* 0/1 j i 行(i) tabOUT n */
            {
                lua_pushnumber(L,0);
            }
            /*  将 0/1 放入行(i) 的 j 位置 */
            lua_settable(L,-4);       /*       i 行(i) tabOUT n */
        }
        lua_insert(L,-2);             /*       行(i) i tabOUT n */

        /* 将行(i) 插入 tabOUT 中的位置 */
        lua_settable(L,2);            /*                tabOUT n */
    }
    return 1;
}

static const struct luaL_Reg LuaMath [] = {{"IdentityMatrix", IdentityMatrix},
                                           {            NULL,           NULL}};

int __declspec(dllexport) luaopen_LuaMath(lua_State *L)
{
    luaL_newlib(L,LuaMath);
    return 1;
}

然后我将其编译为连接到动态库.dll:

gcc -shared -L "<包含 luaX.X.X.dll 的路径>" -l "luaX.X.X" LuaMath.c

当我在 Lua 代码中调用该模块时,如下所示:

require("LuaMath")

输出是:

> require("LuaMath")
检测到多个 Lua VM
堆栈回溯:
        [C]: in ?
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: in ?
>

我哪里错了?

非常感谢。

点赞
用户107090
用户107090

不要将 Lua 库链接到您的 DLL 中。这就是错误信息告诉您的。

2017-05-15 14:09:01
用户851350
用户851350

或许您需要定义一个SYSCFLAGS LUA_BUILD_AS_DLL 然后重新编译lua代码。

gcc -DLUA_BUILD_AS_DLL -c *.c

为什么不使用Lua源码提供的Makefile呢?如果您阅读Makefile,则很容易编译,它会为您设置gcc标志。

cd /path/to/lua-src
make mingw

现在,您应该在/path/to/lua-src/src/中获得lua.exe、luac.exe、lua53.dll。

编译您的模块。

gcc -shared -I/path/to/lua-src/src LuaMath.c -o LuaMath.dll -L/path/to/lua-src/src -llua53
2017-05-20 05:43:45