views:

175

answers:

3

Hi All, I want to write a function(say foo) which takes string as an argument and returns a function pointer ,however this pointer points to 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 seperate files(header and .cpp files). Please help me with the declaration syntax.

Thanks and Regards

+2  A: 

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.

Kim Gräsman
+3  A: 

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.

Adam Rosenfield
thanks a lot all
jeromekjeromepune
+2  A: 

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


}
Naveen