Lua封装类 - 通过DLL将C ++静态方法公开给Lua

我遇到了一个找不到解决方案的问题。我正在使用http://lua-users.org/wiki/CppConvenientLuaWrapperClass中的 Lua 包装类。我们已经能够暴露完整的 API,以及其他附加功能,如串行通信等。

Lua 包装背后的概念是在编译前暴露每个方法,因此当您运行程序时,所有方法都将添加到 Lua 栈中,通过这种方式,您可以执行它们。现在的想法是构建一种类似 Dll 的东西,以完成暴露方法的这个过程。这样,您将不需要发布具有所有暴露方法的版本,而是通过多个 dll 文件加载它们。

我尝试创建另一个表并在该表中注册其他方法,但是这样做会导致以前暴露的方法停止工作。

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

您能做类似的事情吗?我有一些错误的概念吗?

谢谢

哦...我真的不想在这个时候改变我们的包装器。我想我可以设法做到这一点。我添加了一个新的子表,其中将包含要从 Lua 调用的函数名称和 cClosure。

因此,最终我们应该有:

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

即使按这种方式工作也很好。现在我想知道如何引用 lua_settable,以便在将函数添加到application[plugin][pluginFunction]而不是aplication[pluginFunction]时进行公开! 以下是普通函数的曝光方式:

//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 );

有没有想法如何实现将 cclosures 添加到主表(位于mMethodTableIndex处)而不是mainTable \ [functionName]而是 maintable \ [plugin][functionName]?

点赞
用户847349
用户847349

我不确定你是否理解你想要做什么。扩展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用作嵌入式脚本语言,在其中执行Lua代码,也可以将其用作可扩展的脚本语言,使用上面显示的方法进行扩展。两者都是有效的,但你必须考虑你想要做什么。

2013-02-13 15:45:19