I have the following header and CPP:
"Utils.h"
__declspec(dllexport) static char* GetRamMegabytes(char* &FreeMemory);
"Utils.cpp"
char* Utils::HardWare::GetRamMegabytes(char* &FreeMemory)
{
char* TotalMb = "";
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
float freeMemFloat = ((float)statex.ullAvailPhys/1024/1024);
float value =((float)statex.ullTotalPhys/1024/1024);
sprintf(FreeMemory,"%f",value);
sprintf(TotalMb,"%f",freeMemFloat);
return TotalMb;
}
I have my DLL compiled and I'm trying to make a PInvoke from C# with the following code:
[DllImport("LndNativeAssembly.dll", EntryPoint = "?GetRamMegabytes@HardWare@Utils@@SAPADAAPAD@Z", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr GetRamMegaBytes(IntPtr freemem);
I'm trying to call the native function using:
IntPtr free = IntPtr.Zero;
IntPtr res = GetRamMegaBytes(free);
And I get this error:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
FreeMemoryneeds to be passed in with space already allocated and you need to allocateTotalMb, assigning it to""is useless. Also instead of returning a value through a paramater and a return statement have you considered returning a custom struct and adding an accompanying free method.