简体   繁体   中英

Can a C++ dll file be loaded in Lua?

I need to load a DLL file in Lua to connect different APIs. I know that C type dlls can be loaded, but what I have is a dll file produced in C++.

The code (in C++) that produced this library was of the form:

// MyAPI.h

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

which then produced the dll file MyAPI.dll . When I now try to import this in Lua, using:

require "MyAPI"

it immediately gives the error: error loading module 'MyAPI' from file '.\\MyAPI.dll': The specified procedure could not be found . I do not understand what this means, or how to get rid of it. Can C++ libraries in general not be included by Lua (ie should I write another C wrapper?) or is there a way to do this?

You need to export a C function named luaopen_ MyAPI that follows the C-Lua API. The rest of the code can be C++.

My understanding is that you will need to have a C wrapper with a C entry point rather than a C++ entry point. C++ does name mangling so it can change dynamically depending on the compiler as well as the method signature, etc.

Here is Anatomy of a Lua to C Call which you may find helpful.

Also see this stack overflow discussion on what goes on with dll loading .

And here is another stack overflow discussion on require and dll loading .

This is a brief post on the name mangling problem .

Yes, it can be done. Expose a C-function loader luaopen_MyAPI , where you can call a function that uses any kind of C++ Lua Wrapper, such as LuaBridge , LuaBind or others. If your calls in C++ don't conform to the rules of the bindings, such as lifetime management, passing objects by value, etc, you might need to wrap the classes into bindable classes.

For an example see pugilua

  • pugilua_lib.h - module loader API
  • pugilua_lib.cpp - wrapper classes and a LuaBridge binding
  • pugilua.cpp - calling the bindings from the module loader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM