私は次の関数の引数として文字列を取り、関数ポインタを返し、しかし、このポインタポイント機能(foo
言う)書きたい:クラスのメンバである関数を宣言し、関数ポインタをスレッドに返す方法は?
DWORD WINAPI fThread1(LPVOID lparam)
をまた機能(foo
)は、Aのメンバーであります私はそれを定義し、別のファイル(.hpp
と.cpp
ファイル)で宣言します。
宣言の構文を教えてください。
私は次の関数の引数として文字列を取り、関数ポインタを返し、しかし、このポインタポイント機能(foo
言う)書きたい:クラスのメンバである関数を宣言し、関数ポインタをスレッドに返す方法は?
DWORD WINAPI fThread1(LPVOID lparam)
をまた機能(foo
)は、Aのメンバーであります私はそれを定義し、別のファイル(.hpp
と.cpp
ファイル)で宣言します。
宣言の構文を教えてください。
私は、これはあなたが欲しいものだと思う:
class Bob
{
public:
typedef DWORD (__stdcall *ThreadEntryPoint)(LPVOID lparam);
ThreadEntryPoint GetEntryPoint(const std::string& str)
{
// ...
}
};
私はwinbase.hからThreadEntryPoint
の定義を拾い、PTHREAD_START_ROUTINE
が呼ばれます。
ThreadEntryPoint
は、あなたが示した署名を持つ関数への関数ポインタであり、GetEntryPoint
はそのような関数へのポインタを返します。
最も簡単な方法は、関数ポインタのtypedefを使用することです。あなたには、いくつかの理由でのtypedefを使用したくない場合は、
typedef DWORD (WINAPI *ThreadProc)(LPVOID);
class MyClass
{
public:
ThreadProc foo(const std::string & x);
};
...
ThreadProc MyClass::foo(const std::string & x)
{
// return a pointer to an appropriate function
}
また、あなたはこれを行うことができます。
class MyClass
{
public:
DWORD (WINAPI *foo(const std::string & x))(LPVOID);
};
...
DWORD (WINAPI *MyClass::foo(const std::string & x))(LPVOID)
{
// return a pointer to an appropriate function
}
構文はかなり醜いので、typedefの使用を強くお勧めします。
チェックunderstndingのコメント:
//Put this in a header file
class Foo
{
public:
//A understandable name for the function pointer
typedef DWORD (*ThreadFunction)(LPVOID);
//Return the function pointer for the given name
ThreadFunction getFunction(const std::string& name);
};
//Put this in a cpp file
//Define two functions with same signature
DWORD fun1(LPVOID v)
{
return 0;
}
DWORD fun2(LPVOID v)
{
return 0;
}
Foo::ThreadFunction Foo::getFunction(const std::string& name)
{
if(name == "1")
{
//Return the address of the required function
return &fun1;
}
else
{
return &fun2;
}
}
int main()
{
//Get the required function pointer
Foo f;
Foo::ThreadFunction fptr = f.getFunction("1");
//Invoke the function
(*fptr)(NULL);
}
おかげでたくさんのすべて –