0

I'm defining an interface in C# which will be implemented in C#, but called from an unmanaged C++ module as a COM object.

I know what I want/need the C++ API to look like and how I'd define it via ODL:

//args is an array of BSTR e.g VT_ARRAY|VT_BSTR
HRESULT DoMethod(/*[in]*/BSTR name, /*[in]*/VARIANT args);

I'm not sure how to set this up in C# to cause the TLB definition to match this, in regards the VARIANT. Could it be something as simple as the following?

void DoMethod(string name, string args[])

I've been looking around COM/.NET interop documentation but either I've missed the section on this, or simply don't understand what's being described!

As an aside, how can I see what COM definition is being emitted for a given C# interface? Is the DLL/TLB easily inspected?

1 Answer 1

1

If you want a variant on the C++ side (why?) then you need to declare it:

using System.Runtime.InteropServices;

namespace LibraryName {
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IFoo {
        void DoMethod(string name, object args);
    }
}

Register the C# assembly with Regasm.exe /codebase /tlb. The /tlb option generates the type library, you can use it in your C++ code with the #import directive. Which is enough to have a look-see, the LibraryName.tlh file it generates has the declarations. Or you can run Oleview.exe from the Visual Studio Command Prompt and use File > View Typelib to look at it.

Your original instinctive choice is better, string[] shows up as SAFEARRAY* on the C++ side. Less accidents that way.

Sign up to request clarification or add additional context in comments.

3 Comments

So object <--> VARIANT, I found this documented after asking but I'm unsure still how I would create this object to be marshalled as the right type of variant? Could you perhaps add a (pseudo) implementation of DoMethod()? As far as variant Vs safearray - our originally C++ only project has always done it this way rather than pass naked safearrays. I couldn't tell you why, it's nearly 20 years old!
Erm, not sure how that request could make sense, it is the caller that has to create the array and stuff it in a variant. DoMethod() consumes it.
Yeah, you're right. Though if it were an out parameter I'd still be interested in the same basic question, this isn't my need right now... thanks for spotting this.

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.