jeromekjeromepune
jeromekjeromepune

Reputation:

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:

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).

Please help me with the declaration syntax.

Upvotes: 0

Views: 855

Answers (3)

Naveen
Naveen

Reputation: 73473

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


}

Upvotes: 2

Adam Rosenfield
Adam Rosenfield

Reputation: 400454

The easiest way is to use a typedef for the function pointer:

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:

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.

Upvotes: 3

Kim Gräsman
Kim Gräsman

Reputation: 7596

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.

ThreadEntryPoint is a function pointer to a function with the signature you showed, and GetEntryPoint returns a pointer to such a function.

Upvotes: 2

Related Questions