我尝试使用“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/