简体   繁体   English

D3D和COM问题

[英]Problem with D3D & COM

all the D3D interfaces are derived from COM's IUnknown interface, so I though I'd take an easy route for releasing D3D objects and use something like this: 所有D3D接口都是从COM的IUnknown接口派生的,因此尽管我会采取一种简单的方法来发布D3D对象,并使用类似以下的方法:

__inline BOOL SafeRelease(IUnknown*& pUnknown)
{
    if(pUnknown != NULL && FAILED(pUnknown->Release()))
        return FALSE;

    pUnknown = NULL;
    return TRUE;
}

this doesn't work though, as the compiler will generate invalid type conversion error(s), when I try to use it. 但是这不起作用,因为当我尝试使用编译器时,它将生成无效的类型转换错误。 the only way around it I could think of was this: 我能想到的唯一方法是:

__inline BOOL SafeRelease(void* pObject)
{
    IUnknown* pUnknown = static_cast<IUnknown*>pObject;
    if(pUnknown != NULL && FAILED(pUnknown->Release()))
        return FALSE;

    return TRUE;
} 

but then I loose some functionality and it also looks(and is) very dodgy. 但是后来我失去了一些功能,而且看起来也很狡猾。 is there a better way to do this? 有一个更好的方法吗? something that works like my first example would be optimal, though I would like to avoid using any macros(if its possible) 虽然我想避免使用任何宏(如果可能的话),但与我的第一个示例类似的东西将是最佳的

The commonly taken route for dealing with COM resources is to employ RAII and let helper classes like ATLs CComPtr or CComQIPtr handle reference counting for you as far as possible. 处理COM资源的常用途径是使用RAII,并让诸如CComQIPtr CComPtrCComQIPtr类的帮助程序类尽可能多地为您处理引用计数。

void f() {
    CComPtr<IDirect3DDevice> sp3dDev;
    getDevice(&sp3dDev);
    // ... do stuff
} // smart pointer gets destroyed, calls Release() if valid

A template function solves your problem: 模板函数可以解决您的问题:

template<class T>
__inline bool SafeRelease(T*& pUnknown)
{
    if (pUnknown == NULL) return false;
    if (0 == pUnknown->Release()) 
        pUnknown = NULL;
    return true;
}

If you could do what you originally wrote, then you would violate type safety: 如果您可以执行最初编写的内容,则将违反类型安全性:

IDirect3DDevice *blah;
IUnknown *bar;
IUnknown *&unknown= blah;
unknown= bar;

Clearly, assigning bar to unknown would mean that blah points to an IUnknown , which would violate type safety. 显然,将bar分配给unknown意味着blah指向IUnknown ,这将违反类型安全性。

nobugz's solution is probably what you want to do, although I would argue that setting those pointers to NULL doesn't increase the quality of your code. nobugz的解决方案可能是您想要做的,尽管我认为将这些指针设置为NULL不会提高代码的质量。 If you need to ensure that other code won't Release multiple times, you probably should go fix that code rather than making buggy code not fail. 如果您需要确保其他代码不会多次Release ,则可能应该修复该代码,而不是使出错的代码不会失败。

I haven't worked with DirectX in a while but I remember it has a SAFE_RELEASE macro somewhere in it's headers. 我已经有一段时间没有使用DirectX了,但我记得它的标头中有一个SAFE_RELEASE宏。 Google code search shows it's in dxutil.h . Google代码搜索显示它位于dxutil.h

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

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