top of page

Initializing DirectX 12

Writer: Daniel Bellido Chueco
Daniel Bellido Chueco
Oct 7
5 min read

After establishing communication between the WPF application and the native C++ library, the next milestone was introducing DirectX 12.


The objective was to create a graphics device, select an appropriate GPU, and establish a native graphics context that could remain available throughout the application's lifetime.


Unlike the previous milestone, which only involved returning an integer from C++, this implementation required managing native resources across multiple calls and defining how the managed application would control their lifetime.


By the end of this stage, Donatello could successfully initialize DirectX 12 and identify the selected graphics adapter.



Preparing the Native Graphics Backend


I started by extending Donatello.Native with the libraries and headers required for DirectX 12 development.


The native project now links against:

  • d3d12.lib — Provides access to Direct3D 12 functions.

  • dxgi.lib — Provides access to DXGI functionality, including graphics adapter enumeration.


I also introduced GraphicsDevice, a C++ class responsible for initializing and maintaining the graphics device.


The class stores three main objects:

Object

Responsibility

IDXGIFactory6

Enumerating available graphics adapters

IDXGIAdapter1

Representing the selected graphics adapter

ID3D12Device

Creating and managing DirectX 12 graphics resources

Rather than implementing device initialization directly inside the exported API functions, I kept the graphics logic encapsulated within this dedicated class.

This separation allows the native API to remain a communication interface while the graphics subsystem manages its own implementation.



Graphics Adapter Selection


Device initialization begins by creating a DXGI factory through CreateDXGIFactory2.

I then use EnumAdapterByGpuPreference with DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE to enumerate available adapters, prioritizing high-performance GPUs.


The implementation skips software adapters and attempts to create a DirectX 12 device using each suitable candidate.

D3D12CreateDevice(
    adapter.Get(),
    D3D_FEATURE_LEVEL_11_0,
    IID_PPV_ARGS(device.GetAddressOf())
);

The renderer uses the DirectX 12 API while requesting a minimum hardware feature level. More advanced capabilities will require additional checks as the renderer develops.

On my development machine, the initialization successfully selects the NVIDIA GeForce GTX 1050 Ti.



Managing DirectX Resources with RAII


DirectX interfaces use Component Object Model (COM) reference counting, so their lifetime must be managed correctly.

For this implementation, I used Microsoft::WRL::ComPtr to hold the DXGI factory, selected adapter, and DirectX 12 device.

Microsoft::WRL::ComPtr<IDXGIFactory6> factory_;
Microsoft::WRL::ComPtr<IDXGIAdapter1> adapter_;
Microsoft::WRL::ComPtr<ID3D12Device> device_;

ComPtr automatically releases its COM reference when the owning object is destroyed, avoiding the need to manually call Release() for every interface.

This follows the RAII principle, where resource lifetime is tied to object lifetime.

The GraphicsDevice class also disables copying to avoid unintended duplication of the graphics context.


During initialization, I create the required interfaces locally and transfer them into the class only after device creation succeeds. This prevents an unsuccessful initialization attempt from leaving the object partially initialized.



Establishing a Persistent Native Context


My first implementation used a temporary GraphicsDevice object to test whether DirectX 12 initialization succeeded.

Although useful for validating the process, that approach immediately destroyed the graphics device when the function returned.

A future viewport will require the same graphics context to remain available across multiple operations and rendering frames.


To solve this, I introduced an opaque native context:

struct DonatelloGraphics
{
    Donatello::GraphicsDevice device;
};

The public API exposes only a forward declaration of this structure, keeping its implementation hidden from C#.

Two exported functions manage its lifetime:

Donatello_CreateGraphics(...);
Donatello_DestroyGraphics(...);

The creation function allocates and initializes the context, returning an opaque pointer to the application.


The destruction function releases the context when it is no longer required.

This establishes an explicit ownership contract between the managed application and the native graphics backend.



Native Ownership and SafeHandle


An important part of this milestone was ensuring that the native context could be created and destroyed safely.

During creation, I initially manage the context through std::unique_ptr.

auto graphics = std::make_unique<DonatelloGraphics>();

If initialization fails, the object is automatically destroyed.

After successful initialization, ownership is transferred to the native API caller using release().

From that point, the context remains alive until the corresponding destruction function is called.

On the C# side, I introduced a custom SafeHandle:

internal sealed class GraphicsSafeHandle
    : SafeHandleZeroOrMinusOneIsInvalid
{
    public GraphicsSafeHandle()
        : base(ownsHandle: true)
    {
    }

    protected override bool ReleaseHandle()
    {
        NativeMethods.DestroyGraphics(handle);
        return true;
    }
}

This connects managed resource disposal to the native destruction function.

The WPF window stores the graphics context through this wrapper and explicitly disposes of it when the window closes.


The resulting ownership model is straightforward:

  • C++ creates and destroys the native graphics context.

  • C# holds an opaque handle and controls when to request its destruction.

  • SafeHandle provides protection against unmanaged resource leaks.

  • ComPtr manages the underlying DirectX COM references.


At this stage, no GPU rendering commands are submitted. Once rendering is introduced, resource destruction will also need to account for GPU operations that may still be executing.




Error Handling Across the Native Boundary


Graphics initialization can fail for several reasons, including unsupported hardware or unsuccessful resource creation.

To report failures consistently, I designed the native API to return status codes compatible with Windows HRESULT values.

These are exposed as signed 32-bit integers, corresponding to C#'s int.

The application can therefore detect initialization failures and display their hexadecimal error codes for debugging.

The exported creation function also catches C++ exceptions and converts them into appropriate error codes, preventing exceptions from crossing the native-to-managed boundary.

This keeps error handling explicit without requiring the C# application to understand the internal implementation of the graphics subsystem.



Retrieving the Graphics Adapter Information


Once device initialization was working, I wanted the application to identify which GPU had been selected.

DXGI provides this information through DXGI_ADAPTER_DESC1.

Rather than reproducing the entire native structure in C#, I exposed a dedicated function:

Donatello_GetGraphicsAdapterName(...);

The function receives a caller-provided character buffer and its capacity, validates the available space, and copies the adapter description into that buffer.

On Windows, the native wchar_t representation uses UTF-16 code units, allowing the adapter name to be transferred to a Unicode buffer in C#.

The managed application retrieves the result through a StringBuilder, while the native API remains responsible for validating the destination capacity.

This provided my first example of transferring text safely across the language boundary, extending the initial integer-based API introduced in the previous devlog.



Results


By the end of this milestone, Donatello could:

  • Enumerate graphics adapters through DXGI.

  • Select a high-performance hardware adapter.

  • Create a DirectX 12 device.

  • Manage COM interfaces through RAII.

  • Maintain a persistent native graphics context.

  • Control native resource lifetime from C# using SafeHandle.

  • Report initialization errors through the native API.

  • Retrieve and display the selected GPU's name.


The application now displays:


Donatello — Native API v1 — NVIDIA GeForce GTX 1050 Ti

The adapter name is retrieved directly from the native graphics context, confirming that the C# application can communicate with the initialized DirectX 12 subsystem.

There is still no rendering or viewport functionality. This milestone establishes the device initialization and ownership infrastructure required to implement them.



Key Takeaways


The most important part of this implementation was understanding how resource ownership works across the C++ and C# boundary.

Creating a DirectX 12 device is relatively straightforward, but keeping it alive, exposing it safely, reporting failures, and ensuring that every resource is eventually released requires more careful architectural decisions.

Working with ComPtr, std::unique_ptr, opaque handles, and SafeHandle helped me establish a clearer understanding of native resource management and managed interoperability.

These concepts will become increasingly important as Donatello introduces graphics resources, command lists, swap chains, and rendering operations.



What's Next?


The next milestone will focus on enabling DirectX 12 debugging and validation.

Before implementing rendering commands, I want to integrate the DirectX 12 debug layer to identify incorrect API usage and receive more detailed diagnostic information.

This will provide a more reliable development environment for the upcoming rendering infrastructure.


With device initialization and resource ownership established, Donatello is now ready to begin developing its graphics backend.

Recent Posts

See All
Separating Content from Rendering

In the previous milestone, Donatello successfully rendered its first coloured triangle using a custom DirectX 12 graphics pipeline. Although the result was simple, it provided a working foundation for

 
 
 

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Let's build something great

  • LinkedIn

©2022 
Last update: 14/10/2026

bottom of page