无法使用 package.loadlib 在 Lua 中动态加载库
我正在尝试创建一个可以使用 require
或 package.loadlib
加载到 Lua 中的库,但到目前为止我还没有成功。该库本身是用 C++ 编写的,但据我所知,我已经采取了正确导出函数以加载库所需的步骤。简而言之,这是我的 C/C++ 代码的相关部分:
extern "C"
{
// This line is copied from http://gcc.gnu.org/wiki/Visibility
// it's actually in a header, including it here for brevity
#define EXPORT __attribute__((visibility("default")))
EXPORT int luaopen_foo(lua_State* L)
{
luaL_register(L, "Foo", fooL_table);
return 0;
}
}
在我的 Lua 脚本中,我有以下内容:
mylib = package.loadlib("libfoo.so", "luaopen_foo")
print(mylib) -- prints "nil"
The library is being generated from a Makefile generated by CMake, and in the CMakeLists.txt I had attempts compiling with different options ,例如
add_library(foo STATIC ${foo_SOURCES})
add_library(foo MODULE ${foo_SOURCES})
add_library(foo SHARED ${foo_SOURCES})
这些选项似乎都不起作用。
我是否缺少任何步骤来完成这项工作?我很难找到有关如何在网上正确执行此操作的信息,因此欢迎任何指导。我使用的是 Ubuntu 和 gcc 来编译。
I'm trying to create a library that I can load into Lua with require
or package.loadlib
, but I have so far been unsuccessful. The library itself is in C++, but as far as I can tell I've taken the step necessary to properly export the function to load the library. In a nutshell, this is the relevant section of my C/C++ code:
extern "C"
{
// This line is copied from http://gcc.gnu.org/wiki/Visibility
// it's actually in a header, including it here for brevity
#define EXPORT __attribute__((visibility("default")))
EXPORT int luaopen_foo(lua_State* L)
{
luaL_register(L, "Foo", fooL_table);
return 0;
}
}
In my Lua script, I have this:
mylib = package.loadlib("libfoo.so", "luaopen_foo")
print(mylib) -- prints "nil"
The library is being created from a Makefile generated by CMake, and in the CMakeLists.txt I have tried compiling with various options, such as
add_library(foo STATIC ${foo_SOURCES})
add_library(foo MODULE ${foo_SOURCES})
add_library(foo SHARED ${foo_SOURCES})
And none of these options appear to work.
Are there any steps I'm missing to make this work? I'm having a hard time finding information on how to do this properly online so any guidance is welcome. I'm using is Ubuntu with gcc to compile.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Lua 手册中,它说,“
libname
必须是 C 库的完整文件名,如果需要,还包括路径和扩展名。”您的 .so 文件是否位于该目录中且具有该名称?In the Lua manual, it says, "
libname
must be the complete file name of the C library, including if necessary a path and extension." Is your .so file in that directory, with that name?