How to Use Direct3d from Managed Code Using an Unmanaged C++ DLL

This article explains how to use Direct3d, Input and Sound from managed code like C#, using an unmanaged C++ DLL.

The DLL functions need to be declared as extern in the C++ dll
extern "C" __declspec(dllexport) int InitDX(int hWnd,int w, int h)
and imported in the C# application file [DllImport("DXC", SetLastError = true)]
private static extern void InitDX(int hWnd,int w,int h);

The trick is to call the blocking DLL from managed code within a extra thread.

In C# like this:

    int tmph = 0;
     void Video()
     {
         InitDX(tmph,960,640);
     }
 ...
     D = new Display();//the window for direct3d to use
     D.Owner = this;
     D.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     tmph = (int)D.Handle;
     VideoThread = new Thread(new ThreadStart(Video));
     VideoThread.Name = "WOR Video Thread";
     VideoThread.Start(); 

To close the DXUT Interface call the C++ function.

 extern "C" __declspec(dllexport) void CloseDX()
 {
 	PostMessage(DXUTGetHWND(),WM_QUIT,0,0);
 	DXUTShutdown();
 } 

The above code closes the DirectXWindow and shutdowns the UT Interface.

With Application specific calls, one can vary the tile data, which is displayed in the render frame callback.

The Sound Interface could be initiated with:

extern "C" __declspec(dllexport)         private int InitDirectSound()

The Sounds can then be played, controlled and stopped with:

extern "C" __declspec(dllexport) void PlayLobbySound(int nr)

…and other exported functions.

The Direct Input Interface here only uses the keyboard, which is initiated as follows:

extern "C" __declspec(dllexport) private void InitializeInputDevices()

A Call to extern "C" __declspec(dllexport) private bool ReadImmediateData()
fills the buffer and the any key can be compared with
extern "C" __declspec(dllexport) private bool CheckKey(int k)
.

The C++ DLL project must be of Unicode type including the DXUT Comon files.

Library includes are:

  • dxerr.lib
  • dxguid.lib
  • d3dx9d.lib
  • d3d9.lib
  • winmm.lib
  • comctl32.lib
  • odbc32.lib
  • odbccp32.lib
  • Dsound.lib
  • dinput8.lib

For details see the dxc.cpp file in the attachment.

This is part of the Wizard of Wor Arcade game conversion for windows:

Wizard of Wor a c# game using c++ Directx dll
Figure 1

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read