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\n");
    return 1;
  }

  int hello_b(lua_State* L) {
    printf("hello b\n");
    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:\Users\ajanuw\Desktop\hello\x64\Release>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 ./

打包后的结果:

hello\x64\Release>wsl ls *.dll *.lib
hello.dll  hello.lib

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

posted @ 2020-09-14 18:16  Ajanuw  阅读(568)  评论(0编辑  收藏  举报