Saturday, May 16, 2009

.NET COM Interop and Binary Contract Compatibility

When manually creating COM interfaces and classes in .NET, it's critical that the declared order of the .NET operations matches the order in the COM interface. For example, the following IUniformResourceLocator .NET interface matches the layout of the actual COM interface.

using System.Runtime.InteropServices;

 

[

ComImport(),

InterfaceType(ComInterfaceType.InterfaceIsIUnknown),

Guid("CABB0DA0-DA57-11CF-9974-0020AFD79762")

]

public interface IUniformResourceLocator

{

void SetURL(

[In, MarshalAs(UnmanagedType.LPWStr)] string pszURL,

[In, MarshalAs(UnmanagedType.U4)] IURL_SETURL_FLAGS dwInFlags);

 

void GetURL(

[Out, MarshalAs(UnmanagedType.LPWStr)] out string pszURL);

 

void InvokeCommand(

[In] URLINVOKECOMMANDINFO pURLCommandInfo);

}

 

If the methods are declared in alphabetical order (which is what I mistakenly did), then a fairly generic, "Value does not fall within the expected range" error is thrown when calling SetURL.

1 comment:

  1. It is 5 years later, but thank you! This helped out me out this weekend. I wasted several hours before reading this.

    ReplyDelete