使用Lua 5.1的自定义DLL

时间:2016-11-11 12:03:15

标签: dll lua

我试图在Lua中使用自定义DLL。我有一个简单的DLL,例如

extern "C"
{
  static int function_1(lua_State* L)
  {
    std::cout << "[DLL]this is a custom function" << std::endl;
    lua_pushnumber(L, 10);
    return 1;
  }

  __declspec(dllexport) int __cdecl luaopen_myDLL(lua_State* L)
  { 
    L = luaL_newstate();
    luaL_openlibs(L);
    std::cout << "[DLL] being initialized!" << std::endl;

    lua_register(L, "fun1", function_1);
    luaL_dofile(L, "./run.lua");
    return 1;
  }
} 

用VS编写并构建为dll。

在Lua中运行后

package.loadlib("./myDLL.dll", "luaopen_myDLL")() 

require("myDLL")

加载DLL并按预期运行,并运行执行function_1的指定run.lua就好了。

run.lua没有什么特别之处,就像

一样
f = function_1()
print("[Lua] Function_1 says", f, "\n");

我现在的问题是:

  1. 我无法从调用DLL的初始Lua脚本运行function_1()。我试着这样做

    attempt to call global 'function_1' (a nil value)

  2. 我必须在我的C代码中使用L = luaL_newstate();。由于某种原因,它不能使用传递的lua_State *,我认为这是我无法从加载我的DLL的LUA脚本调用注册函数的原因。在运行luaL_newstate()之前,我的lua_State有一个有效的地址,在新状态之后不会改变。
  3. 理论上我可以在我的C库中运行任何Lua脚本来执行已注册的函数,但这对我来说似乎更像是一个肮脏的解决方法。

    我现在的问题是,我是否遗漏了必要的东西?

    p.s。:我正在使用Lua 5.1

1 个答案:

答案 0 :(得分:1)

以下代码应该有效。由于以下原因,可能不会工作:

  • 您用来运行初始Lua脚本(其中包含require("myDLL"))的二进制文件具有不同的Lua版本和/或不使用共享dll。
  • 您在C ++代码中使用的Lua标头与原始lua.exe
  • 具有不同的Lua版本
  • 您将项目与不同的Lua版本链接
  • 您使用您的解决方案再次编译Lua(如果您想使用lua.exe,则必须使用标头并已提供带Lua分发的.lib文件)

要使您的代码在Lua中可用,您必须使用Lua标头获取正确的Lua版本并链接到正确的.lib文件并使用使用共享库的lua.exe(我猜是lua.dll)。

static int function_1(lua_State* L)
{
    std::cout << "[DLL]this is a custom function" << std::endl;
    lua_pushnumber(L, 10);
    return 1;
}

extern "C" int __declspec(dllexport) luaopen_quik(lua_State *L) {
    std::cout << "[DLL] being initialized!" << std::endl;
    lua_register(L, "fun1", function_1);
    luaL_dofile(L, "./run.lua");
    return 0;
}

P上。 S.请提供您的解决方案文件,以便我可以进一步提供帮助,因为它不是代码的问题。 - 它是联系问题。