Search code examples
c#c++visual-studiomfcxunit.net

Exception on loading C# dll on a secondary thread in C++ MFC


I have a .NET Framework 4.8 console application and a test project in the same framework in C#, that use some dlls, with the following structure:

enter image description here

The c++ dll is in MFC.

The problem is the following one:

Scenario A -> If I run the test dll, all dependency dlls are loaded correctly (I can see them from Modules in VS) and in the main thread of CCC.dll, I can execute correctly a method in DDD.dll that is implemented in EEE.dll.

Scenario B -> If I call the same method from a worker thread CWinThread, when I call the same method in DDD.dll I have the following exceptions:

Microsoft C++ exception: EEFileLoadException at memory location 0x000000A6FD9FA230

Could not load file or assembly 'DDD.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified

Also in this case, if I check the loaded modules in VS, I see that DDD.dll and EEE.dll are loaed correctly. I don't understand why it is trying to load DDD.dll one more time (and why it doesn't find it). I tryed to use AFX_MANAGE_STATE(AfxGetStaticModuleState()); in the head of my method where I call the method in DDD.dll but it doesn't fix my problem.

Scenario C -> If I run Scenario A & B from Console app, all works fine and I have no exceptions.


Solution

  • I found the issue. What I understand is that a worker c++ thread can have a different AppDomain from the application one. Since the c# thread has not this "feature", I tried to create the worker thread in c# via c++/cli. In this case the AppDomain is the same as the application one and I have no loading library error anymore.