Eric
Eric

Reputation: 1243

Using a DirectX c++ DLL in a C# WPF or Windows Forms Application

I have written a DX11 renderer using c++. I am now looking for a way to implement an Editor/GUI for it.

Since im pretty used to Windows Forms and WPF C# Applications im thinking about putting my renderer inside a dll, load the dll from a c# application and use it to draw into a defined section of the form. Does this even work with a window handle passed by a managed c# appication and how is the performance if it does?

From my understanding, since the actual communication with the DX11 API would still be directly in c++ and the c# part would only tell the dll what to do the performance loss should be almost nothing. Or is this generally a bad idea and implementing the GUI directly in c++ using a library or D2D is the better approach.

Upvotes: 2

Views: 2345

Answers (1)

Elad Maimoni
Elad Maimoni

Reputation: 4595

In WPF you can use D3DImage which is just like a simple Image in your xaml. The general principle is as follows:

  • Allocate a Direct3D 9 texture, this will be your rendering target.
  • Hand it over to the D3DImage.SetBackBuffer.
  • Put your rendering code inside CompositionTarget.Rendering event handler.

        RenderStuffToTexture();
        d3dImage.Lock();
        d3dImage.AddDirtyRect(new Int32Rect()
        {
            X = 0,
            Y = 0,
            Height = d3dImage.PixelHeight,
            Width = d3dImage.PixelWidth
        });
        d3dImage.Unlock();
    

Since you are using Direct3D 11, you have to use DXGI surface sharing to share the D3D9 textute with D3D11. There are 2 examples I know of that illustrate how to do just that. Microsoft D3D11Image and D3DImageEx (my personal preference, can be found in multiple places online).

Regarding performance, once you use WPF you no longer doing the presentation yourself. You literally write a small render-to-texture logic inside a WPF D3D9-based renderer. So not everything can be controlled including presentation time. From my personal experience, you can definitly render simple scenes at a nice framerate. For a really graphics intensive app and strict FPS requirements I would use a more lightweight (and less intrusive) UI solution.

Note that you can also use WinformHost control to get a HWND and render to it. This has a serious disadvantage if you want to overlay UI controls over the rendered frame - AFAIK you simply can't.

Upvotes: 1

Related Questions