无法在Lua中加载c dll模块

unable to load c dll module in Lua

本文关键字:dll 模块 加载 Lua      更新时间:2023-10-16

我尝试使用"require"在Lua中测试加载c++dll模块,下面是c++模块文件

 #include <stdio.h>
#include <iostream>
extern "C" {
    #include "lua/lualib.h"
    #include "lua/lauxlib.h"
    #include "lua/lua.h"
    __declspec(dllexport) int luaopen_mylib(lua_State* L);
}
using namespace std;
static int libFunc1(lua_State* L)
{
    int n = lua_gettop(L);
    printf("in myfunc stack, arg number: %dn", n);
    if (lua_isstring(L, -1))
    {
        std::cout << lua_tostring(L, -1) << std::endl;
    }
    else
    {
        std::cout << "invalid arg" << std::endl;
    }
    return 1;
}
static const struct luaL_Reg mylib[] = {{"func1", libFunc1}, {NULL, NULL}};
int luaopen_mylib(lua_State* L)
{
    cout << "loading my lib" << endl;
    luaL_newlib(L, mylib);
    return 1;
}

我在msys:中使用g++将这个cpp文件编译成dll

g++    -c -o mylib.o mylib.cpp
g++ -shared -o mylib.dll mylib.o -Llua -llua5.3.0

直到现在一切都很好,我也得到了mylib.dll文件。但是当我尝试加载模块时,我得到了错误消息:

> require("mylib")
error loading module 'mylib' from file '.mylib.dll':
        找不到指定的程序。
stack traceback:
        [C]: in ?
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: in ?

上面的汉字表示:

The specified function could not be found.

我认为"指定的函数"是指"luaopen_mylib",但cpp文件确实有函数:luaopen_mylib,怎么了?

这可能是名称篡改问题。尝试:

extern "C" 
{
    int luaopen_mylib(lua_State* L)
    {
        cout << "loading my lib" << endl;
        luaL_newlib(L, mylib);
        return 1;
    }
}