.NET 中的 COM 类返回 byte[] - 是否释放内存

发布于 2024-09-06 09:57:24 字数 742 浏览 2 评论 0原文

我有一个具有 MyDataObject 类的 COM 组件。有一个具有以下签名的方法:

HRESULT MyDataObject::GetData(long Format, VARIANT* retval)

该 COM 对象在 .NET 应用程序中使用,该方法根据 Format 值返回字符串或字节数组。返回值在 .NET 中转换为 byte[] 并使用。

我怀疑这个方法正在泄漏内存,即从这个方法返回的字节数组需要以某种方式释放。当我调试应用程序时,我看到 GetData(...) 方法调用每次调用都会占用内存。我不知道如何释放这个内存,我可以将其更改为 hGlobal 然后调用 ReleaseHGlobal(...) 或者还有其他方法吗?

已更新


Yes, I am using Task Manager to see how much memory is being used by the sample application. When I start the application, it stays at 16MB but as soon as I hit the test button to call this GetData(...) method about 850 times, the memory starts increasing and the TaskManager shows the application's memory usage increased by about 25MB.

I have a COM component having a MyDataObject class. There is a method with the following signature:

HRESULT MyDataObject::GetData(long Format, VARIANT* retval)

This COM object is used in a .NET application and the method returns either a string or byte array depending on Format value. The returned value is converted to a byte[] in .NET and used.

I suspect this method is leaking memory i.e. The byte array returned from this method needs to be freed up somehow. When I debug the application, I see the GetData(...) method call taking up memory on each call. I am not sure how to free up this memory, Can I change it to hGlobal and then call ReleaseHGlobal(...) or is there any other way?

UPDATED


Yes, I am using Task Manager to see how much memory is being used by the sample application. When I start the application, it stays at 16MB but as soon as I hit the test button to call this GetData(...) method about 850 times, the memory starts increasing and the TaskManager shows the application's memory usage increased by about 25MB.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我们只是彼此的过ke 2024-09-13 09:57:24

CLR 中的 COM 互操作层在将变体的值复制到对象中后已经释放了该变体。即使您想调用 Marshal.FreeCoTaskMem() 但您不能,您也无法获得对原始变体的引用。

你没有说你是如何得出内存泄漏的结论的。不要使用Taskmgr.exe,它会给你错误的印象。通过在小型测试程序中调用此方法数百万次,确保您获得真正的泄漏。如果内存使用量不会无限制地增长并最终导致 OOM,那么就没有真正的泄漏。如果确实崩溃,则怀疑 COM 服务器存在泄漏。就像同时分配字符串和数组但只返回其中之一一样。

The COM interop layer in the CLR already frees the variant after copying its value into an object. Even if you would want to call Marshal.FreeCoTaskMem() you can't, you cannot get a reference to the original variant.

You didn't say how you concluded that you've got a memory leak. Don't use Taskmgr.exe, it will give you the wrong impression. Make sure you've got a real leak by calling this method millions of times in a small test program. If memory usage doesn't grow without bound and eventually cause OOM then you don't have a real leak. If it does crash then suspect the COM server of the leak. Like allocating both the string and the array but returning only one of them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文