Search code examples
c++castingfunction-pointerstypedeface

How to do a function pointer cast without a typedef?


I am using ACE to get functions from a dynamically loaded DLL. The function symbol() below returns a void pointer, which I have to cast back to what it originally is.

typedef cBase * (_cdecl *typeCreateManager)( void );

// ...

ACE_DLL * m_pAceDll = new ACE_DLL;
m_pAceDll->open( "NameOfDll.dll" );

cBase * (_cdecl *pfunc)( void ); // declaration of function pointer
// can be replaced by "typeCreateManager pfunc;"

pfunc = (typeCreateManager)m_pAceDll->symbol("?createManager@@YAPAVcBase@@XZ");
// can be replaced by ???

cBase * pObject = (*pfunc)();

m_pAceDll->close();

Two questions:

  1. Which C++ cast is appropriate instead of the C-like cast? Static or reinterpret?

  2. Can I omit the typedef in the cast? What is the proper syntax? I don't want it to be visible everywhere my DLL is used. Since I only need it at a small number of places in the code I'd like to remove the typedef.


Solution

  • Which C++ cast is appropriate instead of the C-like cast? Static or reinterpret?

    You need reinterpret_cast to convert an object pointer (including void*) to a function pointer.

    Can I omit the typedef in the cast?

    If you have a pointer of the correct type available, you could specify the type of the pointer, rather than a type name:

    cBase * (_cdecl * pfunc)();
    pfunc = reinterpret_cast<decltype(pfunc)>(...);
    

    or you could deduce the pointer type from the cast expression:

    auto pfunc = reinterpret_cast<cBase*(_cdecl *)()>(...);
    

    but you'll need to specify the function type somewhere, and it would probably be clearer and less error-prone to use a suitable typedef for both casts and variable declarations.