VB.NET: Release of COM Objects in Child Functions? RRS feed

  • Question

  • Hi,

    I am currently doing something in PowerPoint. Now if I pass a shape (COM-Object) to a child function I have two questions:

    1. I can't discover any difference if I pass it ByVal or ByRef. Is there any difference in this case at all? How would I notice that? From what I know so far my logic would tell me, that if I pass the shape ByVal a new COM-Object is instantiated or the counter of the RCW is increased by one - where as if I pass it ByRef no such thing happens. Is that right?


    2. Now after the child function has done something with the shape, I continue to work with that shape in the main process. In this case I can not release it at the end of the child function because then I get the error: "An object that has been released from it's underlying RCW can not be accessed anymore." in the main process. That is fine, BUT if I do not release it within the child function I can't release it at all, right? How do I best deal with that, in order not to get any memory leaks or to have any unreleased COM-Objects at the end of my process?


    Many thanks to help my understanding.

    Tuesday, December 1, 2015 9:45 AM


All replies

  • Hello,

    > 1. Is that right?

    No, it is not. The reference counter is not increased in that case. The ReleaseComObject method of the Marshal class decrements the reference count of the specified Runtime Callable Wrapper (RCW) associated with the specified COM object and returns the new value of the reference count of the RCW. This value is typically zero since the RCW keeps just one reference to the wrapped COM object regardless of the number of managed clients calling it. So, you can check out the returned number and see that passing objects by value or by reference doesn't make any sense.

    > 2. Typically callers release objects passed as parameters. However, you can keep your own convention how and where underlying COM objects are released. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Office object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. Read more about that in the  Systematically Releasing Objects article.

    Finally, you may find the When to release COM objects in Office add-ins developed in .NET page helpful.

    Tuesday, December 1, 2015 10:19 AM
  • Many thanks.

    I will start to study all of your hints.

    Wednesday, December 2, 2015 8:26 AM
  • Hi MoD66,

    Very nice, please feel free to open the new thread if you have issues.



    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, December 4, 2015 7:47 AM