简体   繁体   中英

How Do I serialize a COM object in .Net?

我需要使用c#或Delphi使用.net序列化Com对象。这可能吗?

检查您的COM对象是否实现IPersistStreamIPersistMemory或任何其他IPersist变体-最好的选择。

您可以通过将COM对象包装在(可序列化的.NET类中),公开要序列化的字段来实现此目的。

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

不只是通过将对象传递给序列化器,还可以在COM对象包装器上实现ISerializable接口(主互操作程序集也是包装器)并定义自己的序列化。

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM