fett
fett

Reputation: 23

How to implement interface of C# use COM of native C++?

I'm using .Net Core in cross platform, include windows and linux.

I can't use ATL.

I embed the. Net core to my executable program.

I hope expose c++ class instance pointer to .Net Core(C#), and convert to interface of C#.

C++:

class foo : public IDispatch, public IManagedObject, public IInspectable...{} fobj;
extern "C" __declspec(dllexport) foo* WINAPI GetTestObject(){return new foo;}

C#:

[DllImport("foo.dll")]
static extern IntPtr GetTestObject();
[Guid("48DF8E89-57DE-3599-AD7C-B49500EF01C0")]
interface ITest
{
    int func();
}
main(){
    var v = GetTestObject();
    obj = (ITest)Marshal.GetObjectForIUnknown(v);
    obj.func();// exception
    dynamic dobj = Marshal.GetObjectForIUnknown(v);
    dobj.func();// OK, IDispatch::Invoke be called
}

I hope to implement interface ITest of C#.

Upvotes: 0

Views: 467

Answers (2)

fett
fett

Reputation: 23

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]

interface Test

{

}

Upvotes: 0

John Wu
John Wu

Reputation: 52280

What you need is called a Runtime callable wrapper.

Here is a How to article on how to create one.

Upvotes: 2

Related Questions