如何在没有 typedef 的情况下进行函数指针转换?
How to do a function pointer cast without a typedef?
我正在使用 ACE 从动态加载的 DLL 中获取函数。 returns 下面的函数 symbol() 是一个空指针,我必须将其转换回原来的样子。
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();
两个问题:
哪种 C++ 转换更适合代替类 C 转换?静态还是重新诠释?
我可以省略强制转换中的 typedef 吗?什么是正确的语法?我不希望它在使用我的 DLL 的任何地方都可见。因为我只在代码中的少数地方需要它,所以我想删除 typedef。
Which C++ cast is appropriate instead of the C-like cast? Static or reinterpret?
您需要reinterpret_cast
将对象指针(包括void*
)转换为函数指针。
Can I omit the typedef in the cast?
如果您有可用的正确类型的指针,您可以指定指针的类型,而不是类型名称:
cBase * (_cdecl * pfunc)();
pfunc = reinterpret_cast<decltype(pfunc)>(...);
或者您可以从强制转换表达式中推断出指针类型:
auto pfunc = reinterpret_cast<cBase*(_cdecl *)()>(...);
但您需要在某处指定函数类型,使用合适的 typedef
进行强制转换和变量声明可能会更清晰且更不容易出错。
另一种方法是使用联合。
union{
void *data;
cBase* (*pfunc)(void);
}converter;
//...
converter.data = m_pAceDll->symbol("?createManager@@YAPAVcBase@@XZ");
cBase *base = converter.pfunc();
我正在使用 ACE 从动态加载的 DLL 中获取函数。 returns 下面的函数 symbol() 是一个空指针,我必须将其转换回原来的样子。
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();
两个问题:
哪种 C++ 转换更适合代替类 C 转换?静态还是重新诠释?
我可以省略强制转换中的 typedef 吗?什么是正确的语法?我不希望它在使用我的 DLL 的任何地方都可见。因为我只在代码中的少数地方需要它,所以我想删除 typedef。
Which C++ cast is appropriate instead of the C-like cast? Static or reinterpret?
您需要reinterpret_cast
将对象指针(包括void*
)转换为函数指针。
Can I omit the typedef in the cast?
如果您有可用的正确类型的指针,您可以指定指针的类型,而不是类型名称:
cBase * (_cdecl * pfunc)();
pfunc = reinterpret_cast<decltype(pfunc)>(...);
或者您可以从强制转换表达式中推断出指针类型:
auto pfunc = reinterpret_cast<cBase*(_cdecl *)()>(...);
但您需要在某处指定函数类型,使用合适的 typedef
进行强制转换和变量声明可能会更清晰且更不容易出错。
另一种方法是使用联合。
union{
void *data;
cBase* (*pfunc)(void);
}converter;
//...
converter.data = m_pAceDll->symbol("?createManager@@YAPAVcBase@@XZ");
cBase *base = converter.pfunc();