2

その前に、私はそのような巨大なものを使用しました:

int* ShowPopUpMessage = (int*)0x004837F0; //declare
((int (__cdecl*)(const char *, char))ShowPopUpMessage)("You see this message!", 0); //call

うーん、ちょっと紛らわしいと言う必要はないと思います。

今、私はそのような通常の関数ポインタを宣言したい:

int *ShowPopupMessage(const char *, char);

その関数をそのように呼び出すことができるようにするには:

ShowPopupMessage("asd", 0);

しかし、そのポインターに関数アドレスを割り当てることはできません。私は試した:

int *ShowPopupMessage(const char *, char) = (int*)0x004837F0; //error: function "ShowPopupMessage" may not be initialized

//then this
int *ShowPopupMessage(const char *, char);
ShowPopupMessage = 0x004837F0; //nope

ShowPopupMessage = (int*)0x004837F0; //nope

*ShowPopupMessage = 0x004837F0; //nope

*ShowPopupMessage = (int*)0x004837F0; //nope

うーん。他の方法はありますか?

4

4 に答える 4

4

後でコンパイル エラーを解決しようとする場合でも、コンパイラの診断を読む必要があります。「いいえ」と言ったことは本当にありません。

Atypedefは、関数ポインターを返す関数 (または関数ポインター) を宣言する場合に特に便利です。単純な関数ポインター型の式では、次のように書くときに括弧を覚えるだけでよいので、あまり役に立ちません。

int *ShowPopupMessage(const char*, char); // a function declaration
int (*ShowPopupMessage)(const char*, char); // a function pointer definition

どちらも C++ プログラマにとって読みやすいものです。

あなたの場合、(型を 2 回使用する必要があるため) aが望ましいかもしれませんが、受け入れ可能な暗黙的な変換を理解するのに問題があるように見えるので、カーテンtypedefの後ろに問題を隠すつもりはありません。typedef

上記の例では、ほとんどの場合、左側のみを変更しています。C++ では、整数型から (任意の) ポインター型への暗黙的な変換が許可されていません。同様に、オブジェクト ポインター型から関数ポインター型への暗黙的な変換も許可されていません。整数を関数ポインターとして解釈する場合は、キャストが必要です。キャストだけでなくreinterpret_cast、関数ポインター型へのキャストも必要です。

// this is OK (with the cast), but ShowPopupMessage is not a function pointer,
// but a pointer to int
int *ShowPopupMessage = (int*)0xDEADBEEF;

// this is incorrect, as C++ does not allow implicit conversions from
// object pointers to function pointers
int (*ShowPopupMessage)(const char*, char) = (int*)0xDEADBEEF;

// this is OK (assuming you know what you're doing with 0xDEADBEEF)
int (*ShowPopupMessage)(const char*, char) =
        (int(*)(const char*, char))0xDEADBEEF;

// this is preferable in C++ (but it's not valid C)
int (*ShowPopupMessage)(const char*, char) =
        reinterpret_cast<int(*)(const char*, char)>(0xDEADBEEF);

// (this is a possibility in C++11)
#include <functional>
std::function<int(const char*, char)> ShowPopupMessage =
        reinterpret_cast<int(*)(const char*, char)>(0xDEADBEEF);
// it's used in much the same way as function pointers are
// i.e. you call it like you always call them: ShowPopupMessage("", ' ')
于 2012-05-31T11:52:36.963 に答える
3

typedef を使用します。

typedef int (*funptr)(const char *, char);
funptr ShowPopupMessage;

ShowPopupMessage = (funptr) your_address_goes_here;
ShowPopupMessage("hello", 0);
于 2012-05-31T10:15:42.727 に答える
2

これはうまくいくはずです:

{
    typedef int (*funcPtr)(const char *, char);

    funcPtr func = (funcPtr) 0x004837F0;

    func("asd", 0);
}
于 2012-05-31T10:15:16.310 に答える