Robert Bennett Robert Bennett - 3 months ago 18
C++ Question

Using DirectX 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.

Answer

DllMain is a special-case, so you have to be careful about what you do in it. For example, it gets called for every thread that is created in your process by default. Creating COM objects inside a DllMain is not safe because COM creation often involves loading other DLLs and you end up with a 'loader lock' problem. For more information on this see Dynamic-Link Library Best Practices

Your best option here is to have an explicit initialization method which handles creating the Direct3D device that you call explicitly from your main application exe.

Comments