# Why do I get this error about DllMain when using D3D from within a DLL?

I am trying to create a Dll that will handle all my rendering, I am trying to initialize Direct X but I am getting the following error message:

DXGI ERROR: CreateDXGIFactory cannot be called from DllMain. [ MISCELLANEOUS ERROR #76: ] Exception thrown at 0x00007FF978181F28 in Engine.exe: Microsoft C++ exception: _com_error at memory location 0x000000541631BE90.

I never directly call CreateDXGIFactory, I only call D3D11CreateDevice before the program crashes, here is the code for D3D11CreateDevice:

HRESULT hRes;
D3D_FEATURE_LEVEL featureLevel;
m_pConsole->WriteToConsole("Creating D3D11 device !");
hRes = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, D3D11_CREATE_DEVICE_DEBUG, NULL, 0, D3D11_SDK_VERSION, &m_pD3D11Device, &featureLevel, &m_pD3D11DeviceContext);


This function call is not in Dll main it is in an initialize function that is in its own class within the Dll.

• "it is in an initialize function that is in its own class within the Dll" - And at which point is this function called? Might be useful to use a debugger in case it's called from multiple places. – Peter Aug 14 '16 at 14:52

You cannot call DXGICreateFactory directly (or indirectly) from DllMain because the load order of dependent DLLs cannot be guaranteed. Loading DXGI can demand the load of other DLLs depending on OS and driver versions, and that can result in crashes or deadlocks (due to the loader lock).
Verify that this initialization function is not called by any constructors of global objects, as those constructors are executed for those globals just prior to DllMain and suffer the same order-of-operations problems.
Generally you should provide an explicit entry point to your DLL, such as InitializeRendering or whatnot, that invokes any code that will need to directly or indirectly load DLLs or do anything scary that shouldn't be done in DllMain.