D3D 和 D3D 的问题通讯
所有的D3D接口都是从COM的IUnknown接口派生的,所以我想我会采取一种简单的方法来释放D3D对象并使用类似这样的东西:
__inline BOOL SafeRelease(IUnknown*& pUnknown)
{
if(pUnknown != NULL && FAILED(pUnknown->Release()))
return FALSE;
pUnknown = NULL;
return TRUE;
}
但这不起作用,因为编译器将生成无效的类型转换错误,当我尝试使用它时。我能想到的唯一解决办法是:
__inline BOOL SafeRelease(void* pObject)
{
IUnknown* pUnknown = static_cast<IUnknown*>pObject;
if(pUnknown != NULL && FAILED(pUnknown->Release()))
return FALSE;
return TRUE;
}
但后来我失去了一些功能,而且它看起来(而且确实)非常狡猾。有更好的方法吗?像我的第一个例子一样工作的东西将是最佳的,尽管我想避免使用任何宏(如果可能的话)
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:
__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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
处理 COM 资源的常用方法是使用 RAII 并让 ATL 等辅助类
CComPtr
或CComQIPtr
尽可能为您处理引用计数。The commonly taken route for dealing with COM resources is to employ RAII and let helper classes like ATLs
CComPtr
orCComQIPtr
handle reference counting for you as far as possible.模板函数可以解决您的问题:
A template function solves your problem:
如果您可以执行最初编写的操作,那么您将违反类型安全性:
显然,将
bar
分配给unknown
将意味着blah
指向一个IUnknown
,这会违反类型安全。nobugz 的解决方案可能是你想要做的,尽管我认为设置那些指向 NULL 的指针不会提高代码的质量。如果您需要确保其他代码不会多次
Release
,您可能应该修复该代码,而不是让有错误的代码不会失败。If you could do what you originally wrote, then you would violate type safety:
Clearly, assigning
bar
tounknown
would mean thatblah
points to anIUnknown
, which would violate type safety.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. 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.我有一段时间没有使用 DirectX,但我记得它的标头中的某处有一个
SAFE_RELEASE
宏。 Google 代码搜索显示它位于 dxutil.h 中。I haven't worked with DirectX in a while but I remember it has a
SAFE_RELEASE
macro somewhere in it's headers. Google code search shows it's indxutil.h
.