Implementing IUnknown in C#
Asked Answered
L

3

7

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?

Ligation answered 23/5, 2013 at 13:44 Comment(3)
AFAIK IUnknown is implemented implicitly in C#.Preparatory
What is your goal? IUnknown is implemented by the COM-interop automatically. You don't need to do anything.Wagers
@JordanParmer, I wasn't aware of this (I am now :-)). I have an interface (C++) which implements IUnknown, so I wasn't sure how to go about inheriting IUnnkown from the C++ COM interface (if that makes sense)...Ligation
T
8

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.

Try answered 23/5, 2013 at 13:48 Comment(4)
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.Ligation
One reason you'd want to is to allow your COMVisible class to have custom responses for some interface reference. Normally C# takes care of all the wiring of QueryInterface, but sometimes you might want to have a custom response for a specific IID without manually writing a wrapper.Camp
This is not an answer. If you do not understand the viability of the question, inquery.Lehman
@ZverevEvgeniy And yet the author accepted it, so I can't have been completely wrong. Also, this is a 7-year-old question.Try
D
6
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISomeInterface
{
   ...
}

This attribute does ISomeInterface : IUnknown { ... }

Debrief answered 19/11, 2015 at 11:48 Comment(0)
S
1

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().

Streptomycin answered 13/3, 2016 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.