lua调用dll导出的函数

hello.dll

#include "pch.h"
#include "lua.hpp"

#pragma comment(lib, "lua.lib")

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}


extern "C" {
  int hello_a(lua_State* L) {
    printf("hello a
");
    return 1;
  }

  int hello_b(lua_State* L) {
    printf("hello b
");
    return 1;
  }

  __declspec(dllexport) LUALIB_API int __stdcall  luaopen_hello(lua_State* L) {
    lua_register(L, "a", hello_a);
    lua_register(L, "b", hello_b);
    return 1;
  }
}

test.lua

require("hello")

a()
b()

测试

C:UsersajanuwDesktophellox64Release>lua test.lua
hello a
hello b

准备工作:

  1. 将lua源码编译一份lua.lib放在hello/下
  2. hello>wsl cp ../lua-5.4.0/src/*.h ../lua-5.4.0/src/*.hpp ./

打包后的结果:

hellox64Release>wsl ls *.dll *.lib
hello.dll  hello.lib

hello.dlltest.lua放在同级目录后> lua test.lua

原文地址:https://www.cnblogs.com/ajanuw/p/13668224.html