本文介绍了如何将本地CComSafeArray返回到LPSAFEARRAY输出参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 限时删除!! 我有一个COM函数应该通过 LPSAFEARRAY * out参数返回一个SafeArray。 该函数使用ATL的 CComSafeArray 模板类创建SafeArray。 我的naive实现使用 CComSafeArray< T> :: Detach(),以将所有权从本地变量移动到输出参数: void foo(LPSAFEARRAY * psa) { CComSafeArray< VARIANT> ret; ret.Add(CComVariant(42)); * psa = ret.Detach(); } int main() { CComSafeArray< VARIANT> sa; foo(sa.GetSafeArrayPtr()); std :: cout<< sa [0] .lVal } 执行解锁操作,以便当SafeArray的新所有者(main的 sa 这种情况下)销毁锁不为零,并且 Destroy 无法使用 E_UNEXPECTED 解锁SafeArray一个内存泄漏,因为SafeArray没有释放)。 通过COM方法边界将所有权转移到CComSafeArrays的正确方法是什么? 编辑:从单一答案到目前为止,似乎错误是客户端( main )而不是从服务器端( foo ),但我很难相信 CComSafeArray 不是为这个琐碎的用例设计的,必须有一个优雅的方式来获取SafeArray从COM方法到 CComSafeArray 。解决方案问题是你设置接收 CComSafeArray 的内部指针。 使用 Attach()方法将现有的 SAFEARRAY 附加到 CComSafeArray : LPSAFEARRAY ar; foo(& ar); CComSafeArray< VARIANT> sa; sa.Attach(ar); I have a COM function that should return a SafeArray via a LPSAFEARRAY* out parameter.The function creates the SafeArray using ATL's CComSafeArray template class.My naive implementation uses CComSafeArray<T>::Detach() in order to move ownership from the local variable to the output parameter:void foo(LPSAFEARRAY* psa){ CComSafeArray<VARIANT> ret; ret.Add(CComVariant(42)); *psa = ret.Detach();}int main(){ CComSafeArray<VARIANT> sa; foo(sa.GetSafeArrayPtr()); std::cout << sa[0].lVal << std::endl;}The problem is that CComSafeArray::Detach() performs an Unlock operation so that when the new owner of the SafeArray (main's sa in this case) is destroyed the lock isn't zero and Destroy fails to unlock the SafeArray with E_UNEXPECTED (this leads to a memory leak since the SafeArray isn't deallocated).What is the correct way to transfer ownership between to CComSafeArrays through a COM method boundary?Edit: From the single answer so far it seems that the error is on the client side (main) and not from the server side (foo), but I find it hard to believe that CComSafeArray wasn't designed for this trivial use-case, there must be an elegant way to get a SafeArray out of a COM method into a CComSafeArray. 解决方案 The problem is that you set the receiving CComSafeArray's internal pointer directly.Use the Attach() method to attach an existing SAFEARRAY to a CComSafeArray:LPSAFEARRAY ar;foo(&ar);CComSafeArray<VARIANT> sa;sa.Attach(ar); 这篇关于如何将本地CComSafeArray返回到LPSAFEARRAY输出参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-08 19:24