I need serialize a Com Object using .net using c# or Delphi .Net is this possible?
How Do I serialize a COM object in .Net?
3.5k Views Asked by RRUZ AtThere are 6 best solutions below

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.

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

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

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.
You could probably do this by wrapping the COM object in a (serializable) .NET class, exposing the fields that you want serialized.