MFC canned DllMain does not call ExitInstance for DLL_PROCESSS_DETACH? - windows

The canned DllMain for MFC 8.0 does not seem to call ExitInstance when it gets a DLL_PROCESS_DETACH. One possible solution is to define my own DllMain, but how do I tell the linker to use mine and not MFC's?
Or, is there another override which gets called on DLL_PROCESS_DETACH I'm not aware of?

I have had similar issues for a project compiled with /clr. Are you in the same situation? I was never able to trace it to a specific condition, but changing some static initializers to set null cleared it up. I think it has something to do with the order that static destructors are registered.

I'm not sure why your ExitInstance isn't called, but it's possible to define your own DllMain by copying the contents of MFC's dllmodul.cpp file into a file in your dll and adding any extra required functionality. The procedure is documented in this MS knowledge base article. Though it was written for MFC 4.0, I have used this method successfully for apps using MFC 8.0.

Related

How to find out in unmanaged code if it is running in managed context

I am writing an Excel VSTO add-in. This add-in loads and runs unmanaged code.
In the startup code of the unmanaged dll, an invisible window for request handling is created. This function call causes a managed exception (LoaderLock) and if I remove it, everything works. I want to avoid creating an extra version just because of this. Is there a way for the unmanaged code to find out at runtime whether it is running in a managed thread? In this case, I could add a runtime check. The window is only needed in a fully unmanaged environment.
Note 1: The issue only occurs in this Excel add-in; a stand-alone managed console application using the unmanaged dll does not show this problem.
Note 2: I know that there are many things that should not be done from within DllMain. What I am doing has been working for more than a decade in managed and unmanaged environments and I want to keep code changes as small as possible.
Checking if mscoree.dll has been loaded has done the trick for me:
if (::GetModuleHandleW(L"mscoree.dll") == nullptr)
This: Checking if a WIN32 / Unmanaged DLL is loaded from a COM module on runtime and this: What does it mean when code "runs on" the .NET CLR? helped.
As exposed in the comments below, this does not tell which type of thread has loaded the dll, but only whether there is any managed component in the process. A more precise check would still be preferred. For the moment, I can live with this solution.

Running app puts up: "The application has failed to start because XYZ.DLL was not found." BUT it actually runs fine?

I have a question, I came across running an x86 app on XP x64 that throws up a couple (2) of the "The application has failed to start because XYZ.DLL was not found". My question is, it still runs fine! So how does that work? I know if some function is missing you get that and the app doesn't actually run. What causes this message yet it runs fine? I don't think LoadLibrary() would put up a message? Is it from some #pragma comment( lib, "XYZ.lib" ) in a library even if that module not used?
TIA!!
My question is, it still runs fine! So how does that work?
If a DLL function is statically linked and can't be found at runtime, the OS will fail to create and run the process at all. So, the obvious answer is that the DLL function is linked dynamically instead via calls to LoadLibrary() and GetProcAddress() at runtime.
I know if some function is missing you get that and the app doesn't actually run.
If the missing DLL function is linked statically, yes.
What causes this message yet it runs fine? I don't think LoadLibrary() would put up a message?
Actually, it can. Use SetErrorMode() to avoid that. This is stated as much in the LoadLibrary() documentation:
To enable or disable error messages displayed by the loader during DLL loads, use the SetErrorMode function.
See Silently catch windows error popups when calling LoadLibrary().
Is it from some #pragma comment( lib, "XYZ.lib" ) in a library even if that module not used?
Linking to a DLL's .lib creates static linkage to the DLL. Unless the linker has a delay-load feature available AND the project is making use of that feature, in which case any static calls to the lib's referenced DLL functions are converted into runtime calls to LoadLibrary()/GetProcAddress() by the compiler+linker for you.

How to call functions defined by caller of a dll from dll's source in C/C++?

I want to call functions defined by caller of a dll from dll. I am working on a C/C++ application. Main application may or may not use certain dlls as per the configuration provided and both the sides(Main application and dll) need to invoke each others functions. These example explained fairly well how one can create a dll and call it's functions at runtime.
https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=vs-2019
https://learn.microsoft.com/en-us/cpp/build/linking-an-executable-to-a-dll?view=vs-2019
However it doesn't explain how can I call functions defined in Main application from dll.
When I try to declare the same function in dll's headers it throws error saying failed to find function.
How can I tell to linker that certain function will be available at run time. In gcc there is --export-dynamic. This can be used for exporting the symbols and later shared object is able to use these symbols. Is there something similar in windows?
Edit:
Following discussion gives a possible solution, Here caller must pass the function to dll as argument.
How to call a function defined in my exe inside my DLL?
This will be little cumbersome to use in my situation. I am trying to port here a linux application on windows. There are many methods which are called by dll. Passing all of them to dll as function doesn't sound as a good idea however this can be doable as last resort. Other downside I see on taking this approach is, this will require Main application to be changed on every time plug in(dll) wish to use some new function of Main application.

Calling a function in a managed DLL from native Visual C++ code through COM

Apologies in advance for the following verbose question ; I am a COM noob.
Scenario: I need to call a managed DLL built with C# from native Visual C++ code. In my native VC++ code, I do the following after registering "SomeDLL.dll" and generating the "SomeDLL.tlb" file with RegAsm.exe.
Import the TLB file with #import "SomeDLL.tlb"
Use the class MyClass defined in the DLL with CComPtr<MyClass>.
Everything's great! It compiles, and I can run the code etc. It hits the fan when I try to run this application on a different machine (i.e. not the one I compiled it on). I copy all the required DLLs, and I register the same DLL with RegAsm.exe but it doesn't work.
It specifically fails when it tries to initialize the COM library with CoInitialize(0) and returns the S_FALSE error which means
The COM library is already initialized on this thread.
I can confidently state that I have not called this function anywhere else in my code.
Any suggestions?
Hard to help you find that code from here, you're a lot closer. Maybe a DLL that gets injected.
Getting S_FALSE is not an error, getting RPC_E_CHANGED_MODE would be quite bad. Be sure to use the FAILED macro:
HRESULT hr = CoInitialize(0);
if (FAILED(hr)) {
CallNineOneOne(hr);
exit(hr);
}
Maybe you called OleInitialize or another function which calls ComInitialize behind the scenes.
Anyway, it does not matter to call CoInitialize several times per thread if you match each of them with a call to CoUninitialize

Implicit vs. Explicit linking to a DLL

When one should implicitly or explicitly link to a DLL and what are common practices or pitfalls?
It is fairly rare to explicitly link a DLL. Mostly because it is painful and error prone. You need to write a function pointer declaration for the exported function and get the LoadLibrary + GetProcAddress + FreeLibrary code right. You'd do so only if you need a runtime dependency on a plug-in style DLL or want to select from a set of DLLs based on configuration. Or to deal with versioning, an API function that's only available on later versions of Windows for example. Explicit linking is the default for COM and .NET DLLs.
More background info in this MSDN Library article.
I'm assuming you refer to linking using a .lib vs loading a DLL dynamically using LoadLibrary().
Loading a DLL statically by linking to its .lib is generally safer. The linking stage checks that all the entry points exist in compile time and there is no chance you'll load a DLL that doesn't have the function you're expecting. It is also easier not to have to use GetProcAddress().
So generally you should use dynamic loading only when it is absolutely required.
I agree with other who answered you already (Hans Passant and shoosh). I want add only two things:
1) One common scenario when you have to use LoadLibrary and GetProcAddress is the following: you want use some new API existing in new versions of Windows only, but the API are not critical in your application. So you test with LoadLibrary and GetProcAddress whether the function which you need exist, and use it in the case. What your program do if the functions not exist depend total from your implementation.
2) There are one important options which you not included in your question: delayed loading of DLLs. In this case the operating system will load the DLL when one of its functions is called and not at the application start. It allows to use import libraries (.lib files) in some scenarios where explicitly linking should be used at the first look. Moreover it improve the startup time of the applications and are wide used by Windows itself. So the way is also recommended.

Resources