提取 Wx 类

lua-users home
wiki

本教程/示例旨在帮助您了解如何在 lua_CFunction 中从 Lua 堆栈中提取 [wxLua] userdata 对象。

这里使用的基本过程是获取 wxWidgets 类的 wxLuaState 对象中的类标签,然后使用该标签在 C++ 中获取实际的 wxLua 对象。

类标签是用于标识 wxWidgets 类类型(wxDCwxWindowwxCheckBox 等)的整数 ID,存在于 wxLuaBindClass 结构中。该标签也存储在 wxLua 推送到 Lua 的所有 userdata 对象的元表中,用于标识 userdata 是什么,另请参阅“int wxlua_ttag(lua_State* L, int stack_idx)”。

wxLuaBindClass 结构是 wxLua 绑定用于将 C++ 版的 wxWidget 类绑定到 Lua 的描述。

struct wxLuaBindClass // defines a LUA C++ class interface
{
    const char      *name;          // name of the class
    wxLuaBindMethod *methods;       // pointer to methods for this class
    int              methods_n;     // number of methods
    wxClassInfo     *classInfo;     // pointer to the wxClassInfo associated with this class
    int             *class_tag;     // lua tag for user data allocated by ourselves
    const char      *baseclassName; // name of base class
    wxLuaBindClass  *baseclass;     // Pointer to the base class or NULL for none.
                                    // This member is set after all the bindings are
                                    // registered since the base class may be from
                                    // a different module (a library perhaps).
                                    // See wxLuaBinding::SetBaseClass

    wxLuaBindDefine* enums;         // Class member enums (if any)
    int              enums_n;       // number of enums
};
(您可以在 wxlbind.h 中找到 wxLuaBindClass 的定义)

class_tag 成员就是您想要的。它是一个指向在启动时定义的常量的指针。(这些结构在 modules/wxbind/src/wxXXX_bind.cpp 中初始化)。那么如何获取特定 wxWidget 类的类描述呢?

wxLuaBindClass* wxLuaState::GetLuaClass(const char* class_name)

此方法返回一个指向 wxLuaBindClass 结构的指针,该结构包含可用于检索实际对象的类标签。class_name 应指定 wxWidgets 类的 C++ 名称,例如 "wxPaintDC""wxFrame"

void* wxLuaState::GetUserDataType(int index, int tag)

index 是您用来访问堆栈中任何其他元素的正常堆栈索引。tag 是从 wxLuaBindClass::class_tag 返回的值(请记住,此成员是指向 int 的指针)。GetUserDataType 将返回所请求的对象。

在 modules/wxbind/src/*.cpp 文件中有许多 wxLua 如何从 Lua 获取和推送对象的示例,这些文件是从 bindings/wxwidgets/*.i 中的接口文件生成的。这些示例使用了实际的整数变量,如果您包含声明它们的头文件或自己声明它们为 extern 变量,您也可以使用它们。

Example

int Paint(lua_State* L)
{
	wxLuaState wxlState(L);
	wxPaintDC *dc;

	unsigned int tag;
	wxLuaBindClass* wxl_class;

	wxl_class = wxlState.GetLuaClass("wxPaintDC");     // get the WXLUACLASS
	tag = *wxl_class->class_tag;                       // remember to dereference the class_tag member!
	dc = (wxPaintDC*)wxlState.GetUserDataType(1, tag); // get the actual object

	  // ///////////////////////// //
	 //    Paint code goes here   //
	// ///////////////////////// //

	return 0;
}

备注:wxLuaBindClass:定义在 modules/wxlua/include/wxlbind.h

Discussion

我大约在一年前开始研究这个问题,当时我正在使用 wxLua 编写一个快速简陋的地图编辑器,并且想确保我能够优化 paint handler。我花了一些时间才弄清楚,并想确保它被文档化,这样其他想做同样事情的人就不必像我一样深入研究和解读源代码。 --Nick

RecentChanges · preferences
编辑 · 历史
最后编辑于 2007 年 7 月 25 日 下午 8:01 GMT (diff)