1

Does anybody know whether the following implementation of a C++ interface in C# is correct, particularly with regards to the marshaling of the GUID type.

The original C++ we are implementing:

[
    object,
    pointer_default(unique),
    uuid(Z703B6E9-A050-4C3C-A050-6A5F4EE32767)
]
interface IThing: IUnknown
{
    [propget] HRESULT Prop1([out, retval] GUID* prop1); 
    [propget] HRESULT Prop2([out, retval] EnumProp2* prop2);
    [propget] HRESULT Prop3([out, retval] HSTRING* prop3);
};

The converted interface in our C# COM assembly:

[ComVisible(true), Guid("Z703B6E9-A050-4C3C-A050-6A5F4EE32767"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IThing
{
    Guid Prop1 { get; }
    EnumProp2 Prop2 { get; }
    string Prop3 { get; }
}

The concrete class:

public class Thing : IThing
{    
    public Thing(Guid prop1, EnumProp2 prop2, string prop3)
    {
        Prop1 = prop1;
        Prop2 = prop2;
        Prop3 = prop3;
    }

    public Guid Prop1 { get; }
    public EnumProp2 Prop2 { get; }
    public string Prop3 { get; }
}
2
  • the Guid structures of C# and the <windows.h> definition of GUID have a different grouping, but they are "binary compatible" as they're both 16 byte long and bytes are ordered consistently: stackoverflow.com/a/14891293/1132334 so it should work. do you have any reason to believe your ComVisible interface would be wrong? can you just test it? Commented Mar 12, 2017 at 18:53
  • ok looks like it should by a byte[16] which you can get using Guid.ToByteArray. reference source shows that the Guid struct is a complex type and does not expose the raw bits. Commented Mar 12, 2017 at 19:05

1 Answer 1

1

It turns out the issue was actually not marshaling the Guid structure, but the string.

It seems that when moving a string from the managed CLR heap to the unmanaged heap, the default marshaling type is UnmanagedType.BStr (unicode character string, length-prefixed) - and the host app in this case required a different marshal type:

public string Name { [return: MarshalAs(UnmanagedType.HString)]get; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.