You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过IntPtr确定其指向内存的字节大小?

如何通过IntPtr确定指向内存区域的字节大小?

我手里有个表示内存地址的IntPtr,想找个简便方法确定它指向的内存区域的字节大小。之前试着用循环遍历的方式实现,结果触发了访问违规,根本拿不到结果。注意,我没有Bitmap,问题和Bitmap无关,就只有这个IntPtr。

后来改成直接把内存数据写入流(存文件),数据能成功写入,但就算加了try/catch还是会触发访问违规。现在的情况是:如果预先知道内存大小,操作就能正常完成;但面对未知大小的Scan0时,虽然最终能得到结果,但必然会触发访问违规——如果能捕获这个违规,就能提前确定内存的大小了。

相关代码如下:

public record struct MemoryPointer(IntPtr Scan0, int Size)
{
    public async Task Save(string filePath)
    {
        byte[] bytes = new byte[Size];
        using Stream stream = File.Create(filePath);
        unsafe
        {
            byte* pointer = (byte*)Scan0;
            for (int index = 0; index < Size; index++, pointer++)
            {
                bytes[index] = *pointer;
            }
        }
        await stream.WriteAsync(bytes);
    }
}

内容的提问来源于stack exchange,提问作者FSO931s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 14:17:03