DllMain 入口点 DLL_PROCESS_DETACH

DllMain entry point DLL_PROCESS_DETACH

我有一个从 C# 进程调用的 C++ DLL...

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

这里是 dll 入口点...

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;
    }

我像这样得到一个连接和四个分离...

附上 分离 分离 分离 分离

谁能解释为什么?

进程只调用一次函数。

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

当触发 DLL_THREAD_ATTACHDLL_THREAD_DETACHDLL_PROCESS_DETACH 时,您的代码将在控制台中写入 "Detach"。如果你只想要 DLL_PROCESS_DETACH 在你的 switch:

中添加 break 语句
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;
}

或者简单地省略未使用的案例。