TEDSON TEDSON - 3 months ago 37
C++ Question

DllMain entry point DLL_PROCESS_DETACH

I have a c++ dll, called from a c# process...

[DllImport(@"My.dll", EntryPoint = "Function1", CallingConvention = CallingConvention.Cdecl)]
public static extern bool MyFunction(int id1, int id2, [MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder Name);


Here is dll entry point...

switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
std::cout << "Attach" << std::endl;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
std::cout << "Detach" << std::endl;
break;
}


I get one attach and four detach like so...

Attach
Detach
Detach
Detach
Detach

Can anyone explain why?

The process makes just one call to the function.

Answer
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
    std::cout << "Detach" << std::endl;
    break;

Your code will write "Detach" in console when DLL_THREAD_ATTACH, DLL_THREAD_DETACH or DLL_PROCESS_DETACH is fired. If you want only DLL_PROCESS_DETACH add break statements in your switch:

switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
    std::cout << "Attach" << std::endl;
    break;
case DLL_THREAD_ATTACH:
    break;
case DLL_THREAD_DETACH:
    break;
case DLL_PROCESS_DETACH:
    std::cout << "Detach" << std::endl;
    break;
}

or simply omit unused cases.

Comments