CSharp解析完MIDI后想顺手写个内存占用显示,一般自己写CPP程序喜欢写这么个东西时时查看内存,防止内存爆炸等沙雕操作。
搜了下,CSharp一般写法是
Process CurrentProcess = Process.GetCurrentProcess();
CurrentProcess.WorkingSet64
确实比CPP写起来简单不少,在XNA下测试成功。
来到Unity下测试返回值一直是0,google也是如此。
没人知道为什么不行,不过有人提到插件市场似乎有插件可以在Unity中显示进程内存。
我简单粗暴的就想到可能是调用了Win32 API。
翻出之前的CPP DLL测试工程,把CPP调用进程和内存的代码简单封装了下。
#include <windows.h>
#include <psapi.h>
#ifdef __cplusplus // If used by C++ code,
extern "C"
{ // we need to export the C interface
#endif
int memoryUsage;
DWORD processID;
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
__declspec(dllexport) void InitMemInfo()
{
processID = GetCurrentProcessId();
if (processID)
{
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
}
else
{
memoryUsage = -1;
}
}
__declspec(dllexport) void DestroyMemInfo()
{
if (hProcess) CloseHandle(hProcess);
}
__declspec(dllexport) int Frame()
{
if (hProcess)
{
if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)))
{
memoryUsage = pmc.WorkingSetSize;
}
}
return memoryUsage;
}
#ifdef __cplusplus
}
#endif
Unity中再简单调用下
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Profiling;
public class MemoryManager : MonoBehaviour
{
public string memInfo = "";
[DllImport("MemInfo")]
public static extern void InitMemInfo();
[DllImport("MemInfo")]
public static extern void DestroyMemInfo();
[DllImport("MemInfo")]
public static extern int Frame();
private double inv10241024 = 0.00000095367431640625;
void Start()
{
InitMemInfo();
}
void OnDestroy()
{
DestroyMemInfo();
}
void Update()
{
float memoryUsed = (float)(Frame() * inv10241024);
memInfo = memoryUsed.ToString("0.000") + " MB";
}
private void OnGUI()
{
GUI.Label(new Rect(0, 0, 400, 50), memInfo);
}
}
解决,有种脱裤子放屁的蛋疼感,但是似乎只有这样才能显示出进程内存集,估计直接导入某个系统dll直接调用Win32 API函数也行,懒没实验,验证下可行性就算了,时间过的太快,乱七八糟的折腾一下就凌晨3点半了...睡觉