【问题标题】:Can a C++ dll file be loaded in Lua?可以在 Lua 中加载 C++ dll 文件吗?
【发布时间】:2013-12-15 19:39:35
【问题描述】:

我需要在 Lua 中加载一个 DLL 文件来连接不同的 API。我知道可以加载 C 类型的 dll,但我拥有的是用 C++ 生成的 dll 文件。

生成这个库的代码(C++)是这样的:

// MyAPI.h

namespace MyAPI
{
    public class MyFirstClass
    {
        public: 
           MyFirstClass();
           void performSomeMethod(int arg);
    }
}

然后生成 dll 文件MyAPI.dll。当我现在尝试在 Lua 中导入它时,使用:

require "MyAPI"

它立即给出错误:error loading module 'MyAPI' from file '.\MyAPI.dll': The specified procedure could not be found。我不明白这意味着什么,或者如何摆脱它。 Lua 通常不能包含 C++ 库(即我应该编写另一个 C 包装器吗?)还是有办法做到这一点?

【问题讨论】:

    标签: c++ dll lua


    【解决方案1】:

    您需要导出一个遵循 C-Lua API 的名为 luaopen_ MyAPI 的 C 函数。其余代码可以是 C++。

    【讨论】:

      【解决方案2】:

      我的理解是,您将需要一个带有 C 入口点而不是 C++ 入口点的 C 包装器。 C++ 确实名称修饰,因此它可以根据编译器以及方法签名等动态更改。

      这里是Anatomy of a Lua to C Call,您可能会觉得有帮助。

      另见stack overflow discussion on what goes on with dll loading

      这是另一个stack overflow discussion on require and dll loading

      这是brief post on the name mangling problem

      【讨论】:

        【解决方案3】:

        是的,可以做到。公开一个 C 函数加载器 luaopen_MyAPI,您可以在其中调用使用任何类型的 C++ Lua Wrapper 的函数,例如 LuaBridgeLuaBind 或其他。如果您在 C++ 中的调用不符合绑定规则,例如生命周期管理、按值传递对象等,您可能需要将类包装成可绑定类。

        示例见pugilua

        • pugilua_lib.h - 模块加载器 API
        • pugilua_lib.cpp - 包装类和 LuaBridge 绑定
        • pugilua.cpp - 从模块加载器调用绑定

        【讨论】:

        • @Yellow 很高兴能帮上忙!
        猜你喜欢
        • 2011-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 2021-03-25
        相关资源
        最近更新 更多