萃取 Wx 類別

lua-users home
wiki

此教學課程/範例旨在協助您了解如何在 lua_CFunction 中從 Lua 堆疊中萃取出 [wxLua] 使用者資料物件。

在此使用之基本程序是從 wxWidgets 類別的 `wxLuaState` 物件取得稱為類別標籤的資訊,並使用該標籤在 C++ 中取得實際的 wxLua 物件。

類別標籤是一個整數 ID,用於識別 wxWidgets 類別類型(`wxDC`、`wxWindow`、`wxCheckBox` 等),且可在 `wxLuaBindClass` 結構中找到。標籤也儲存在 wxLua 推入 Lua 的所有使用者資料物件的元資料表中,以識別使用者資料為何,另請參閱「int wxlua_ttag(lua_State* L, int stack_idx)」

`wxLuaBindClass` 結構是 wxWidget 類別 C++ 版本的說明,而 wxLua 繫結使用該結構將類別繫結至 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` 成員。它是指向開機時定義的常數的指標。(結構會在模組/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` 會傳回所要求的物件。

在模組/wxbind/src/*.cpp 檔案中有很多 wxLua 如何從 Lua 取得並將物件推入 Lua 的範例,這些檔案是從繫結/wxwidgets/*.i 中的介面檔案產生的。這些檔案使用實際整數變數,如果您包含它們宣告的標頭或宣告它們為 extern 變數,您也可以使用這些變數。

範例

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:在模組/wxlua/include/wxlbind.h 中定義

討論

我實際上是在一陣子之前開始研究這件事,當時我使用 wxLua 嘗試撰寫快速而簡單的地圖編輯器,而且想要確認我可以最佳化繪製處理程式。我花了一段時間才弄清楚,而且想要確認可以將它記錄下來,這樣其他人就不需要像我一樣深入剖析和解譯原始程式碼才做得到。--Nick

最近變更 · 偏好設定
編輯 · 歷程
上次編輯於 2007 年 7 月 26 日,上午 2:01 GMT (比較)