foo
文字列を引数として取り、関数ポインターを返す関数 (たとえば ) を作成したいのですが、このポインターは次の関数を指しています。
DWORD WINAPI fThread1(LPVOID lparam)
また、関数 ( ) はクラスのメンバーであるため、定義して別のファイル (およびファイル)foo
で宣言します。.hpp
.cpp
宣言構文について教えてください。
foo
文字列を引数として取り、関数ポインターを返す関数 (たとえば ) を作成したいのですが、このポインターは次の関数を指しています。
DWORD WINAPI fThread1(LPVOID lparam)
また、関数 ( ) はクラスのメンバーであるため、定義して別のファイル (およびファイル)foo
で宣言します。.hpp
.cpp
宣言構文について教えてください。
最も簡単な方法は、関数ポインターに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
}
または、何らかの理由でtypedefを使用したくない場合は、次のようにすることができます。
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を使用することを強くお勧めします。
私はこれがあなたが望むものだと思います:
class Bob
{
public:
typedef DWORD (__stdcall *ThreadEntryPoint)(LPVOID lparam);
ThreadEntryPoint GetEntryPoint(const std::string& str)
{
// ...
}
};
ThreadEntryPoint
私はwinbase.hからの定義をピックアップしましたPTHREAD_START_ROUTINE
。
ThreadEntryPoint
は、指定したシグニチャを持つ関数への関数ポインタであり、GetEntryPoint
そのような関数へのポインタを返します。
理解のためにコメントを確認してください:
//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);
}