Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass C# object to COM by value

I'm trying to use a COM interface from C# that exposes the following interface as generated by tlbimp:

[Guid("7DDCEDF4-3B78-460E-BB34-C7496FD3CD56")]
[TypeLibType(TypeLibTypeFlags.FDual | TypeLibTypeFlags.FNonExtensible | TypeLibTypeFlags.FDispatchable)]
public interface IFred 
{
    [DispId(1)]
    IBarney Pall { get; set; }
}

[Guid("E390230E-EE9C-4819-BC19-08DAB808AEA9")]
[TypeLibType(TypeLibTypeFlags.FDual | TypeLibTypeFlags.FNonExtensible | TypeLibTypeFlags.FDispatchable)]
public interface IBarney
{
    [DispId(1)]
    double Wilma { get; set; }
}

The generated wrapper assembly does not contain an implementation for the IBarney interface. I've created a C# structure that implements the IBarney interface like this:

[Guid("2C61BA37-7047-43DB-84B1-83B4268CF77B")]
[ComVisible(true)]
public struct Barney : IBarney
{
    public double Wilma { get; set; }
}

Which "works", the question now is, will a Barney instance be marshalled by value or by reference? This is important due to the network overhead involved. Ideally executing something like:

fredInstance.Pall = new Barney { Wilma = 0.37 };

will result in a single network round trip. How can I verify this, or how can I tell COM interop my Barney structure should always be marshalled by value?

Update:

Given the comment from Hans Passant. What would be the 'proper' way to design this? What would be the IDL needed to allow for a simple structure to be usable as a value for a 'property' of a COM interface? Looking at the IDL from which the interfaces are generated that I'm currently using adding a coclass declaration with a default IBarney interface would be enough, right?

like image 572
Bas Bossink Avatar asked Apr 08 '16 09:04

Bas Bossink


1 Answers

A couple comments... Don't know if this will be an answer or not...

1) I would think that you should make your interfaces [ComVisible(true)]

2) Why do you define Barney as a struct? It should be a class. Unlike C++ where the only difference between a class and a struct is the default of private vs public members, C# structs and classes are fundamentally different.

like image 141
Joseph Willcoxson Avatar answered Oct 02 '22 14:10

Joseph Willcoxson