我想编写一个函数(比如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);
}