Search code examples
c#dllimport

Inject dll into current process with C#


So my question is a bit different from the other ones posted on this website, in theory, the thing I'm looking for should be far simpler than an injector that injects DLLs into 'any' process.

I have a process that we can refer to as game.exe that loads a series of dll when it launches. These dlls are written in C# and are basically 'scripts' that I can edit without any problem. I wrote a DLL in C++ that when it is injected into the game.exe process with any generic injector 'nop(s)' a series of addresses. I have confirmed the c++ dll works as intended.

Now back to my question, I wish to write in c# code that automatically injects the c++ dll into the game.exe process not 'any' process. The reason I said this should be easier is that the c# dlls are already running basically in the same 'space' as the game.exe so it should be easier to do?

Thanks in advance. In case the c++ code is needed here it is:

constexpr AddrDescriptor addresses[] = { {0x1001bbea, 2}, {0x1001bc4d, 2}, {0x1001bc61, 7} };

DWORD WINAPI EntryPoint(LPVOID _arguments)
{
    for (size_t i = 0; i < (sizeof(addresses) / sizeof(AddrDescriptor)); i++)
    {
        addresses[i].nop_address();
    }
    return 0x1337;
}

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        ::CreateThread(0, 0, static_cast<LPTHREAD_START_ROUTINE>(EntryPoint), 0, 0, 0);
        [[fallthrough]];
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;

Edit 1: A kind user pointed me to another question on this website. It is helpful but if I may ask a clarification. Using dll export in c++: (Reference code above)

extern "C"
{
    __declspec(dllexport) DWORD WINAPI EntryPoint(LPVOID _arguments)
    {
        for (size_t i = 0; i < (sizeof(addresses) / sizeof(AddrDescriptor)); i++)
        {
            addresses[i].nop_address();
        }
        return 0x1337;
    }
}

Would it be possible to now import this function and call it in C# what about the datatypes DWORD WINAPI(LPVOID...) I am not sure how something like this could be done in C#


Solution

  • This solved my answer: C++ code

    extern "C" 
    {
        __declspec(dllexport) int NopTheFrickOut() 
        {
            for (size_t i = 0; i < (sizeof(addresses) / sizeof(AddrDescriptor)); i++)
            {
                addresses[i].nop_address();
            }
            return 0x1337;
        }
    }
    

    C# Code:

    public class ExtensionScript : BaseScript
    {
            [DllImport("RemoveTeknoChecks.dll", CallingConvention = CallingConvention.Cdecl)]
            public static extern int NopTheFrickOut(); 
    ...
    }
    Calling NopTheFrickOut() in the main function of the C# DLl correctly nops the addresses.