SharpDX is a low level wrapper for the DirectX API. The main source of documentation is available from DirectX Graphics and Gaming. Most of the resources available on internet are mostly for C++.
COM, Dispose pattern and Finalizer
Most of the DirectX API exposes services through COM interfaces. The base interface of COM objects is called
IUnknown and provides the following methods:
HRESULT QueryInterface(ref Guid interfaceGuid, out IntPtr pComObj)
Each COM object contains an internal reference counter and is destroyed only when the
ReleaseReference() is called and the counter goes to 0.
All SharpDX COM objects inherit from ComObject which implements the
Dispose() method is actually a shorthand to the COM method
ComObjectin SharpDX is not disposed by the .NET finalizer. If a COM object is not released by a call to
ReleaseReference(), it will not release the native object and memory attached to it.
ComObject exposes the underlying COM pointer through the property
NativePointer. In most situations, you won’t have to use this pointer directly.
Note also that many properties and methods in the DirectX APIs are returning COM objects. In SharpDX, most of the time, if you call these methods to get a COM object, you will get different .NET object instance even if the underlying COM pointer is the same, but calling the COM method has incremented the reference to the returned COM object, and should be disposed/released accordingly.
Almost all Windows APIs use an integer as a return value for all the methods and functions. It is usually called the
- a value
< 0means that there was an error
- a value
== 0is a success
- a value
> 0is sometimes used to return a non-error status depending on the method
While there are some common HRESULT values defined (like for COM
NotImplementedInterface), most of the DirectX APIs have their own set of HRESULT/error codes (for example: DXGI error HRESULT)
In SharpDX, most of the methods automatically throw a
SharpDXException if the
< 0. The exception contains the
HRESULT is often not enough to debug a method call. But fortunately, most of the DirectX APIs provide a debug layer that can be activated. For example, you can activate detailed debug logs for Direct3D11:
d3d11Device = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug);
Note that you can see this log in the Visual Studio Output if you debug your application and that you have enabled
Enable native code debuggingin your .NET project.
Check the DirectX documentation debug layer specific to the API for more details.