Lua包装类-通过DLL向Lua公开c++静态方法

Lua Wrapper Class - Exposing c++ static methods to Lua through a DLL

本文关键字:Lua c++ 静态方法 公开 DLL 包装类 -通过      更新时间:2023-10-16

我终于遇到了一个在这里找不到解决方案的问题。我使用的是在这里找到的Lua包装类http://lua-users.org/wiki/CppConvenientLuaWrapperClass.我们已经能够公开一个完整的API和更多的其他功能,如串行通信等

这个LuaWrapper背后的概念是,你在编译之前公开每个方法,所以当你运行程序时,所有方法都会被添加到LuaStack中,这样你就可以执行它们。现在的想法是构建一种Dll,以完成公开方法的过程。这样你就不需要发布一个包含所有公开方法的版本,而是通过多个dll文件加载它们。

我曾尝试创建另一个表并在该表中注册其他方法,但这样一来,以前公开的方法就无法工作了。

我能想到的另一种方法是创建一个dll,但在C中,它包含所有想要的方法,并将其直接加载到Lua。但我认为换一种方式会更好。

你能做类似的事情吗?我是不是有什么错误的想法?

感谢

哼。。。我真的不想在这个时候改变我们的包装。我想我可以做到的。我没有为插件函数添加一个新表,而是添加了一个新的子表,它将包含要从Lua调用的函数名称和cClose。所以最后我们应该有:

application.functionName()
application.plugin.functionName()

即使这样工作,它也会做得很好。现在我想知道,当我们将要添加到application[plugin][pluginFunction]而不是application[pluginFunction]的函数公开时,如何引用lua_stable?!这就是正常功能的暴露方式:

//mState is a pointer to a Lua_State
lua_pushstring( mState, functionName );
//methodDesc is a pointer to an object that describes the function arguments/returns 
lua_pushlightuserdata( mState, methodDesc );
//exposeMethodProxy is the method that is responsible for conneting lua c-calls to the c-functions
lua_pushcclosure( mState, exposedMethodProxy, 1 );
//mMethodTableIndex is a member variable that contains the index of the table tha hold all exposed functions
lua_settable( mState, mMethodTableIndex );

关于如何实现不将cclosure添加到主表(在mMethodTableIndex)中作为mainTable[functionName],而是添加到mainTable[plugin][functionNane],有什么想法吗。?

我不确定,您是否清楚自己想要做什么。扩展lua的典型方法是用一个方法编写一个DLL,该方法使用lua API注册C++类型和C函数。要方便地绑定C++函数和类,可以使用LuaBridge。此类绑定的示例如下:https://github.com/d-led/xerceslua

xerceslua模块DLL的头只包含一个函数:

#include <lua.hpp>
void register_xerceslua (lua_State* L);

在实现内部,LuaBridge用于绑定到C++:

#include "xerceslua_lib.h"
#include <lua.hpp>
#include <LuaBridge.h>
void register_xerceslua (lua_State* L) {
...
luabridge::getGlobalNamespace(L)
    .beginNamespace("xerces")
    .addVariable("version",&version,false)
...

在Lua中,您可以访问公开的C++API:

assert(require 'xerceslua')
local parser=xerces.XercesDOMParser()
parser:loadGrammar("Employee.dtd",xerces.GrammarType.DTDGrammarType)

您既可以将Lua用作嵌入式脚本语言,也可以将其用作可扩展脚本语言,使用上面显示的方法进行扩展。两者都是有效的,但你必须考虑,你到底想做什么。