我有以下标题和 CPP:
“实用程序.h”
__declspec(dllexport) static char* GetRamMegabytes(char* &FreeMemory);
“实用程序.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;
}
我已经编译了我的 DLL,我正在尝试使用以下代码从 C# 制作一个 PInvoke:
[DllImport("LndNativeAssembly.dll", EntryPoint = "?GetRamMegabytes@HardWare@Utils@@SAPADAAPAD@Z", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr GetRamMegaBytes(IntPtr freemem);
我正在尝试使用以下方法调用本机函数:
IntPtr free = IntPtr.Zero;
IntPtr res = GetRamMegaBytes(free);
我得到这个错误:
尝试读取或写入受保护的内存。这通常表明其他内存已损坏。