首頁 > 後端開發 > C++ > 主體

如何在 C 中的 `void*` 和指向成員函數的指標之間安全地進行轉換?

Linda Hamilton
發布: 2024-10-27 20:06:02
原創
172 人瀏覽過

How to Safely Cast Between `void*` and a Pointer to a Member Function in C  ?

void* 和指向成員函數的指標之間的轉換

在C 程式設計世界中,void* 和指向成員函數的指標之間的轉換成員函數可能是一個真正令人頭痛的問題。讓我們深入研究一個具體問題來說明這個挑戰。

考慮以下程式碼片段:

<code class="cpp">template <class T>
int call_int_function(lua_State *L) 
{
    void (T::*method)(int, int) = reinterpret_cast<void (T::*)(int, int)>(lua_touserdata(L, lua_upvalueindex(1))); // <-- problematic line
    T *obj = reinterpret_cast<T *>(lua_touserdata(L, 1));

    (obj->*method)(lua_tointeger(L, 2), lua_tointeger(L, 3));
    return 0;
}</code>
登入後複製

這裡,GCC 抱怨從 void* 到 void (T::*) 的轉換(int, int) 無效。那麼,解決方案是什麼?

理解問題

理解問題需要更深入地研究成員函數指標的本質。與指向位址的常規指標不同,指向成員函數的指標要複雜得多。它們包含特定於編譯器實作和類別成員佈局的資訊。

替代方法

事實是,您不能直接將 void* 轉換為指標到成員函數。建議的解決方案是將成員函數包裝在常規函數中並傳回該函數。方法如下:

<code class="cpp">template <class T>
int call_int_function(lua_State *L) 
{
    void (*method)(T*, int, int) = reinterpret_cast<void (*)(T*, int, int)>(lua_touserdata(L, lua_upvalueindex(1)));
    T *obj = reinterpret_cast<T *>(lua_touserdata(L, 1));

    method(obj, lua_tointeger(L, 2), lua_tointeger(L, 3));
    return 0;
}</code>
登入後複製

這種方法之所以有效,是因為我們現在正在轉換為常規函數指針,該指針可以存儲在 void* 中並毫無問題地檢索。

以上是如何在 C 中的 `void*` 和指向成員函數的指標之間安全地進行轉換?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!