C ++ DLL:
#include "stdafx.h" #include "windows.h" #include "psapi.h" #include "stdlib.h" typedef struct PROCINF { DWORD dwPID; LPWSTR lpMainModName; } *LPPROCINF; extern "C" __declspec(dllexport) void GetProcessInfo(LPPROCINF lppi) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, lppi->dwPID); if (hProcess == NULL) return; MessageBox(NULL, L"GET MAIN MOD NAME", NULL, NULL); // // Get process main module name. // lppi->lpMainModName = (LPWSTR)malloc(MAX_PATH * sizeof(wchar_t)); GetModuleFileNameEx((HMODULE)hProcess, NULL, lppi->lpMainModName, MAX_PATH * sizeof(wchar_t)); CloseHandle(hProcess); } C #:
[StructLayout(LayoutKind.Sequential)] struct PROCINF { public uint dwPID; [MarshalAs(UnmanagedType.LPWStr)] public string lpMainModName; } [DllImport("my.dll", CallingConvention = CallingConvention.Cdecl)] static extern void GetProcessInfo(ref PROCINF info); // ... PROCINF pinfo = new PROCINF(); pinfo.dwPID = 3604; GetProcessInfo(ref pinfo); MessageBox.Show("PID: " + pinfo.dwPID + Environment.NewLine + "Main module: " + pinfo.lpMainModName); After the completion of GetProcessInfo , the program immediately crashes, and without errors. What is the problem I can not understand, because it seems to be importing correctly (if you remove GetModuleFileNameEx and malloc , replacing filling the value with an empty string, everything will work fine).