[英]how to declare a function which is member of a class and returns a function pointer to a thread?
I want to write a function (say foo
) which takes string as an argument and returns a function pointer, however this pointer points to the following function: 我想编写一个将字符串作为参数并返回一个函数指针的函数(例如
foo
),但是该指针指向以下函数:
DWORD WINAPI fThread1(LPVOID lparam)
Also the function ( foo
) is member of a class, so I will be defining it and declaring it in separate files ( .hpp
and .cpp
files). 另外,函数(
foo
)是类的成员,因此我将对其进行定义并在单独的文件( .hpp
和.cpp
文件)中进行声明。
Please help me with the declaration syntax. 请帮助我声明语法。
The easiest way is to use a typedef for the function pointer: 最简单的方法是对函数指针使用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
}
Alternatively, if you don't want to use a typedef for some reason, you can do this: 或者,如果由于某种原因不想使用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
}
The syntax is rather ugly, so I highly recommend using a typedef. 语法很丑陋,因此我强烈建议使用typedef。
I think this is what you want: 我认为这是您想要的:
class Bob
{
public:
typedef DWORD (__stdcall *ThreadEntryPoint)(LPVOID lparam);
ThreadEntryPoint GetEntryPoint(const std::string& str)
{
// ...
}
};
I picked up the definition of ThreadEntryPoint
from winbase.h, there called PTHREAD_START_ROUTINE
. 我从winbase.h中获得了
ThreadEntryPoint
的定义,该定义称为PTHREAD_START_ROUTINE
。
ThreadEntryPoint
is a function pointer to a function with the signature you showed, and GetEntryPoint
returns a pointer to such a function. ThreadEntryPoint
是指向具有您显示的签名的函数的函数指针,而GetEntryPoint
返回指向该函数的指针。
Check the comments for 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.