简体   繁体   中英

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.

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.

Another way of doing that is using unions.

union{
    void *data;
    cBase* (*pfunc)(void);
}converter;

//...

converter.data = m_pAceDll->symbol("?createManager@@YAPAVcBase@@XZ");
cBase *base = converter.pfunc();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM