简体   繁体   English

强制转换函数指针Release()的正确方法

[英]Correct way to cast function pointer Release()

I have this error when try to cast function on code below : 尝试在以下代码上强制转换函数时出现此错误:

error C2440: 'type cast' : cannot convert from 'overloaded-function' to 'ULONG (__stdcall *)(void)' 错误C2440:“类型转换”:无法从“重载函数”转换为“ ULONG(__stdcall *)(void)”

HRESULT hr = RealCoGetClassObject ( rclsid, dwClsContext, pServerInfo, riid, ppv );

if ( hr == S_OK )
{
    IUnknown * iukn = (IUnknown *)ppv;
    ULONG (WINAPI * RealRelease)() = (ULONG (WINAPI *)(void))(iukn->Release);
}

HRESULT hr = RealCoGetClassObject ( rclsid, dwClsContext, pServerInfo, riid, ppv )

ppv parameter here is supposed to be a pointer to your variable, which is going to be initialized with an interface pointer. 此处的ppv参数应该是指向变量的指针,该变量将使用接口指针进行初始化。 Even though your fragment does not give a clear idea what you are trying to do, the post-call cast looks like you are not passing the proper pointer at the time of the call already. 即使您的片段没有清楚地知道您要做什么,但调用后的强制转换看起来像您在调用时尚未传递正确的指针。 You are expected to cast the argument like this: 您应该像这样强制转换参数:

IUnknown * iukn;
HRESULT hr = RealCoGetClassObject ( rclsid, dwClsContext, pServerInfo, riid, 
    (VOID**) &iukn);
if(SUCCEEDED(hr))
{
    // NOTE: Hey, we got it into `iukn`
    // ...
    iukn->Release();

Or, otherwise, if you are sure that ppv is valid by the time of the call, and you, for instance, want to replace the returned poniter, then the cast is like this: 或者,否则,如果你确信ppv有效的呼叫的时间,而你,例如,要更换回poniter,然后投是这样的:

HRESULT hr = RealCoGetClassObject ( rclsid, dwClsContext, pServerInfo, riid, 
    ppv);
if(SUCCEEDED(hr))
{
    IUnknown*& iukn = *((IUnknown**) ppv);
    iukn->Release(); // Drop the returned thing
    iukn = ... // Put our stuff there

IUnknown::Release is a method, not a function. IUnknown::Release是方法而不是函数。 So you have to use a method pointer instead of function pointer: 因此,您必须使用方法指针而不是函数指针:

typedef ULONG(STDMETHODCALLTYPE IUnknown::*ReleaseMethodPtr) (void);
ReleaseMethodPtr realRelease = &IUnknown::Release;

// for calling the method, you also need an instance pointer
(iukn->*realRelease)();

Having said that and not really knowing what your intent is, i don't think this is what you want. 话虽如此,但我并不真正知道您的意图是什么,我认为这不是您想要的。 Because IUnknown::Release is a (pure) virtual method, calling the method pointer will always do exactly the same as just calling iukn->Release() . 因为IUnknown::Release是一个(纯)虚拟方法,所以调用方法指针将始终与调用iukn->Release()完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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