How Do I serialize a COM object in .Net?

主宰稳场 提交于 2019-12-11 09:21:55

问题


I need serialize a Com Object using .net using c# or Delphi .Net is this possible?


回答1:


You could probably do this by wrapping the COM object in a (serializable) .NET class, exposing the fields that you want serialized.




回答2:


Check to see if you COM object implements IPersistStream, IPersistMemory or any other of the IPersist variants -- that would be your best bet.




回答3:


You can get a Managed Object through GetObjectForIUnknown Method. And then, you can serialize this managed object.




回答4:


Not simply by passing object to serializer - implement ISerializable interface on COM object wrapper (primary interop assembly is a wrapper too) and define your own serialization.




回答5:


I have been able to serialize COM objects brought into C# via standard runtime-callable-wrapper COM interop.

This should work as long as the object being serialized uses the type of the interop-generated class - not an interface.

Say that the type of the object you want to serialize as SomeType in the original / native code. In the Visual Studio object browser you should see several rough equivalents in the interop library:

  • Interface SomeType

  • Interface _SomeType

  • Class SomeTypeClass

It is the last one which must be used for serialization, apparently.

(At least this is how VB6-based classes show up).

To get this to work, set a reference in C# code to the COM DLL. Visual Studio should autogenerate an interop DLL. (The process of generating the interop DLL involves inspecting the typelib metadata of the COM DLL and using that to generate managed classes. So all the information needed for reflection-based serialization to work ought to be available.)

Then, some sample code:

    var settings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,                
    };

    var serializer = JsonSerializer.Create(settings);

    using (var gz = new GZipStream(File.OpenWrite(filespec), CompressionMode.Compress))
    using (var sw = new StreamWriter(gz))
    using (var writer = new JsonTextWriter(sw))
    {
        serializer.Serialize(writer, objectToSerialize);
    }

This should write out the JSON serialized version of objectToSerialize to a GZIP-compressed file.


Note - this answer was based on info in another question.




回答6:


I am not sure there will be difference in how you serialize your data in C++, .Net or in any other language. COM object is like a class and can be serialized by getting each data member and serializing it .I did like this in C++.

I think this should be same in .Net unless there are specific APIs to do it.



来源:https://stackoverflow.com/questions/1085620/how-do-i-serialize-a-com-object-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!