c++ - 无法在Lua中加载c dll模块

标签 c++ dll lua

我尝试使用“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: %d\n", 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;
    }
}

关于c++ - 无法在Lua中加载c dll模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57287988/

相关文章:

c - Lua调用C函数的性能

io - 在Lua中读取整个文件

c++ - 'Excel.exe' 的调试信息找不到或不匹配

c++ - 在 UnitTesting (cppunit) 中使用另一个文件中定义的结构时出错

c# - 让 .net DLL 作为 Windows 服务运行的简单方法

c++ - 如何从 PathCompactPath 的 Wnd 句柄获取 DC 句柄?

c++ - 将静态库链接到dll

c++ - 断言失败CV_Assert(CV_IS_MAT(objectPoints)&& CV_IS_MAT(imagePoints)&& CV_IS_MAT(A)&& CV_IS_MAT(rvec)&& CV_IS_MAT(tvec))

C++ 继承、成员和冗余数据

json - Lua-cjson -> require ("cjson") 成功,然后调用 cjson.encode 时出错