Search code examples
c#c++callbackdllimportdllexport

dllimport how to get which application called function in unmanaged dll


I have 1 unmanaged C++ dll with dllexport functions and 3 managed C# application that use unmanaged dll functions with dllimport , okay everything works fine.

I need to know in C++ dll , How can I get a value that tells me which C# application called it from outside.

please look at image below :

dll image

  • now,when client.exe calls function1 from unmanaged dll , a message shows up "client.exe called me!"
  • now,when console.exe calls function1 from unmanaged dll , a message shows up "console.exe called me!"
  • now,when pure.exe calls function1 from unmanaged dll , a message shows up "pure.exe called me!"

I need unmanaged library finds out it by its own, I don't want send anything extra from C# application like getting C# file path and send it to function.

Can it be possible? if yes , How can I do it?


Solution

  • This should work:

    constexpr DWORD bufsize = 32768;
    WCHAR *calling_application = new WCHAR [bufsize];
    DWORD nSize = GetModuleFileNameW (NULL, calling_application, bufsize);
    
    if (nSize == 0 || nSize == bufsize)
    {
        // panic, should never happen
    }
    
    // ...
    
    delete [] calling_application;
    

    Documentation here:

    https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197%28v=vs.85%29.aspx