MindSystem
MindSystem

Reputation: 11

Get the name of the exe which invoke my dll

I have a C# Project which Invoke a C++ dll And before returning the value in the C++ dll, I would like to check the name of the C# exe which invoke my method. Can you advice me please?

I Load the c++ dll like this:

[DllImport("MindSystem.dll", 
           EntryPoint = "MindSystemPlusPlus",
           CharSet = CharSet.Ansi,
           CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)] 
public static extern IntPtr MindSystemPlusPlus(int value); 

And when I load it, I want that the c++ dll check the name of the exe which invoke it

Edit: I tried this code, but the output in c# is in strange characters :

char fileName[MAX_PATH + 1];
GetModuleFileNameA(NULL, fileName, MAX_PATH + 1);
return fileName;

Upvotes: 1

Views: 2015

Answers (4)

jacekbe
jacekbe

Reputation: 609

You can call GetModuleFileName function. NULL as first parameter means that path to the executable of the current process is requested.

std::string expectedPath("C:\\expected.exe");

TCHAR fileName[MAX_PATH + 1];
DWORD charsWritten = GetModuleFileName(NULL, fileName, MAX_PATH + 1);
if (charsWritten != 0)
{
    if (expectedPath == fileName)
    {
        // do something
    }
}

Upvotes: 1

Alexander Higgins
Alexander Higgins

Reputation: 6923

It depends.

If you are using c++ with /clr you can use read the name of the Process returned from Process::GetCurrentProcess().

In native code in Windows you can use GetModuleFileName()

In Linux or MAC there are different options depending on your platform.

Upvotes: 0

Richard Hodges
Richard Hodges

Reputation: 69854

#include <windows.h>
#include <shellapi.h>

int argc = 0;
auto wargv = CommandLineToArgvW(GetCommandLineW(), &argc);

auto program_path = wargv[0];

...


LocalFree(wargv);

documentation:

Upvotes: 0

MKR
MKR

Reputation: 20085

You should try using GetModuleFileName() function. You can get the full path of the exe. Keep in mind if your DLL is loaded by more than one applications then returned file path will refer to only one of them.

Upvotes: 1

Related Questions