1

In C#, is there an easy way to call a COM object method from a native pointer?

    [DllImport("d3d11.dll", CallingConvention = CallingConvention.StdCall)]
    private unsafe static extern int D3D11CreateDevice(
        void* arg0, int arg1, void* arg2, int   arg3, void* arg4,
        int   arg5, int arg6, void* arg7, void* arg8, void* arg9);

    public static void CreateDevice()
    {
        unsafe
        {
            IntPtr deviceOut;
            IntPtr immediateContextOut;
            int featureLevelRef;

            D3D11CreateDevice(
                (void*)IntPtr.Zero,
                1,
                (void*)IntPtr.Zero,
                32,
                (void*)IntPtr.Zero,
                0,
                7,
                &deviceOut,
                &featureLevelRef,
                &immediateContextOut);
        }
    }

In the code above, I get deviceOut whose type is ID3D11Device*. The ID3D11Device interface has a bunch of methods such as CreateBuffer().

Can I call some of these methods using deviceOut pointer? Thank you in advance.

1
  • You'd need to declare the interface. This has been done, avoid inventing that wheel. Both SlimDX and SharpDX are favored .NET wrappers for DX11. Commented Mar 8, 2013 at 23:08

1 Answer 1

2

If you have a pointer to a COM object you can convert it into an instance of the object via GetObjectForIUnknown.

IntPtr ptr = ...;
object unk = Marshal.GetObjectForIUnknown(ptr);
ID3D11Device dev = (ID3D11Device)unk;

From there you will be able to call the CreateBuffer and other methods

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

1 Comment

I had to change my comment I made a little while ago. Oddly enough, when you create a DirectX COM object like an IDXGIFactory interface it will already have a ref count greater than zero! I suppose Windows already has one alive or something and it just passed you the pointer to it rather than creating a brand new one from scratch. This seems to be true for other DirectX COM objects as well, like I noticed IDXGIAdapterX interfaces may have a ref count of 4 to 6 already when you obtain them.

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.