Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing IUnknown in C#

I've been looking for an example of how to implement IUnknown in C#, but haven't found any decent references or solutions to this.

Should it be as simple as...

public interface IUnknown
{
    UInt32 AddRef();
    UInt32 QueryInterface([In] IntPtr riid, [Out] IntPtr ppvObject);
    UInt32 Release();
}

...or is there more to it?

like image 922
Matthew Layton Avatar asked May 23 '13 13:05

Matthew Layton


3 Answers

Why would you want to implement IUnknown? That's a COM interface. If you want to interoperate with COM, use the .Net/COM bridge, which implements IUnknown for you.

like image 135
Sebastian Redl Avatar answered Oct 09 '22 01:10

Sebastian Redl


[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISomeInterface
{
   ...
}

This attribute does ISomeInterface : IUnknown { ... }

like image 27
plexusilnur Avatar answered Oct 09 '22 00:10

plexusilnur


Asked was: { ... Just out of interest, the Direct2D interface, ID2D1Factory inherits from IUnknown, so presumably I would still need to implement this interface with .NET...I'm not sure what I would do here exactly. – series0ne May 24 '13 at 8:51 ... } And the answer is no. The whole point of deriving a class from IUnknown is so that your class does not have to implement anything IUknown does for you. It will take care of things like QueryInterface and AddRefCount automatically. You don't do a thing in C# or C++ even. In C++ you then CoCreateInstance(), and in C# it is Activator.CreateInstance().

like image 41
Kirk Augustin Avatar answered Oct 09 '22 00:10

Kirk Augustin