question

JiShirley-1989 avatar image
0 Votes"
JiShirley-1989 asked JeanineZhang-MSFT commented

How to release the c# generated COM object when C + + calls

I generated the corresponding COM interface for C# project and tried to call it in C++ project.
The code is roughly as follows:
C# side

 namespace XmlHelper
 {
     [Guid("XXXXXXXX")]
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     public interface IXmlHelper
     {
         IXmlParser CreateParser(string xmlString);
     }

     [Guid("XXXXXXXX")]
     public class MyXmlHelper : IXmlHelper
     {
         public IXmlHelper CreateParser(xmlString)
         {
               ....
               MyXmlParser c = new MyXmlParser(xmlString);
               return c;
         }
     }

     [Guid("XXXXXXXX")]    
     [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
     public interface IXmlParser
     {
         string ParseString(get;)
         .....
         void Dispose();
     }

     [Guid("XXXXXXXX")]    
     class MyXmlParser : IXmlParser, IDisposable
     {
         private string xmlString;
         private NameTable nt;
         private XmlNamespaceManager nsmgr;
         private XmlParserContext context;
         private XmlTextReader reader;
         private bool disposed = false;

         public MyXmlParser(string smlString)
         {
             nt = new NameTable();
             nsmgr = new XmlNamespaceManager(nt);
             nsmgr.AddNamespace(String.Empty, "urn:Xml");
             context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
             reader = new XmlTextReader(xmlString, XmlNodeType.Element, context);
             reader.WhitespaceHandling = WhitespaceHanding.None;
         }

         ~MyXmlParser()
         {
             Dispose(false);
         }

         public void Dispose()
         {
             Dispose(true);
             GC.SuppressFinalize(this);
         }

         protected virtual void Dispose(bool disposing)
         {
            if(this.disposed)
             {
                 if(disposing)
                 {
                     reader.Close();
                     nsmgr.RemoveNamespace(String.Empty, "urn:Xml");
                 }
             }
             disposed = true;
         }

 ......

C++ side

 CComPtr<IXmlHelper> pXmlHelper;
 pXmlHelper.CoCreateInstance(CLSID_XML_HELPER);
 CComPtr<IXmlParser> pParser;
 pXmlHelper->CreateParser(L"XXXX", &pParser);
 pParser->Dispose();
 pParser.Attach(nullptr);
 pXmlHelper.Attach(nullptr);

I'm not sure whether the release method on the C + + side is correct.
And GC.SuppressFinalize(this); Is it necessary on the C# side?
Could you help me answer it?

dotnet-csharpc++
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I read this description, then my implementation is feasible I think.

0 Votes 0 ·

0 Answers