如何声明一个类成员的函数并返回一个线程的函数指针?

时间:2009-08-28 05:24:14

标签: c++ multithreading visual-c++ function-pointers

我想编写一个函数(比如foo),它将字符串作为参数并返回一个函数指针,但是这个指针指向以下函数:

DWORD WINAPI fThread1(LPVOID lparam)

此外,函数(foo)是一个类的成员,因此我将对其进行定义,并将其声明为单独的文件(.hpp.cpp文件)。

请帮我说明声明。

3 个答案:

答案 0 :(得分:3)

最简单的方法是使用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。

答案 1 :(得分:2)

我认为这就是你想要的:

class Bob
{
public:
   typedef DWORD (__stdcall *ThreadEntryPoint)(LPVOID lparam);

   ThreadEntryPoint GetEntryPoint(const std::string& str)
   {
      // ...
   }
};

我从winbase.h中选择了ThreadEntryPoint的定义,称为PTHREAD_START_ROUTINE

ThreadEntryPoint是一个函数指针,指向一个带有你所显示签名的函数,GetEntryPoint返回一个指向这样一个函数的指针。

答案 2 :(得分:2)

检查评论以便理解:

//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);


}
相关问题