无法使用 package.loadlib 在 Lua 中动态加载库

发布于 2024-12-03 21:14:04 字数 1016 浏览 1 评论 0原文

我正在尝试创建一个可以使用 requirepackage.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深居我梦 2024-12-10 21:14:04

在 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文