Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't Direct2D and DirectWrite use traditional COM objects?

I'm toying with a little 2D game engine in C# and decided to use Direct2D and DirectWrite for rendering. I know there's the Windows API Code Pack and SlimDX, but I'd really like to dig in and write an interface from scratch. I'm trying to do it without Managed C++, but Direct2D and DirectWrite don't appear to use traditional COM objects. They define interfaces that derive from IUnknown, but there appears to be no way to actually use them from C# with COM interop. There are IIDs in d2d1.h, but no CLSID.

Of course, I'm really new to COM interop, so perhaps I'm just missing something. Can someone shed some light on this situation?

like image 473
David Brown Avatar asked May 14 '10 21:05

David Brown


1 Answers

Got it. You can't create the objects directly, but d2d1.dll contains an export called D2D1CreateFactory that returns an ID2DFactory interface. Using this, you can implement a Direct2D wrapper without Managed C++.

public static class Direct2D1Util {
    public const string IID_ID2D1Factory =
        "06152247-6f50-465a-9245-118bfd3b6007";

    [DllImport("d2d1.dll", PreserveSig = false)]
    [return: MarshalAs(UnmanagedType.Interface)]
    private static extern object D2D1CreateFactory(D2D1_FACTORY_TYPE factoryType,
        [MarshalAs(UnmanagedType.LPStruct)] Guid riid,
        D2D1_FACTORY_OPTIONS pFactoryOptions);

    public static ID2D1Factory CreateFactory() {
        D2D1_FACTORY_OPTIONS opts = new D2D1_FACTORY_OPTIONS();
        object factory = D2D1CreateFactory(
            D2D1_FACTORY_TYPE.D2D1_FACTORY_TYPE_SINGLE_THREADED,
            new Guid(IID_ID2D1Factory), opts);
        return (ID2D1Factory)factory;
    }
}

I won't include all of the types, because they're all defined in d2d1.h, but here's how to use the code to get a factory:

ID2DFactory factory = Direct2D1Util.CreateFactory();

Make sure your ID2DFactory interface has the appropriate Guid and InterfaceType(ComInterfaceType.InterfaceIsIUnknown) attributes.

like image 135
David Brown Avatar answered Nov 04 '22 15:11

David Brown