Search code examples
c#c++-cli

Calling a static C# method from a managed C++/CLI thread


I seem to be having issue with calling static C# methods.

I currently have 2 DLLs that I inject into an ancient legacy app and then execute a static method as seen in the code below:

Module.cs

using System;

namespace Debugger
{
    public static class Module
    {
        public static void Initialize()
        {
            Console.WriteLine("YES");
        }
    }
}

dllmain.cpp

#include "stdafx.h"

#include <windows.h>

#pragma once

#pragma managed

using namespace System;
using namespace System::Reflection;
using namespace Debugger;

DWORD WINAPI MainThread(LPVOID param)
{
    AllocConsole();

    Console::WriteLine("Test");

    Debugger::Module::Initialize();

    FreeLibraryAndExitThread((HMODULE)param, 0);

    return 0;
}

#pragma unmanaged

HMODULE hModule;
BOOL APIENTRY DllMain(HINSTANCE hInstance, DWORD reason, LPVOID reserved) 
{
    switch (reason) 
    {
        case DLL_PROCESS_ATTACH:
            CreateThread(0, 0, MainThread, hModule, 0, 0);
            break;
        case DLL_PROCESS_DETACH:
            FreeLibrary(hModule);
            break;
    }
    return true;
}

As a result: I get the console open, the 'Test' message pops up but 'YES' doesn't - instead, the app crashes.


Solution

  • Moving the DLL to the same folder as executable I'm injecting into fixed the issue.