尝试读取或写入受保护的内存。这通常表明 c# 中的其他内存已损坏(访问冲突)

Posted

技术标签:

【中文标题】尝试读取或写入受保护的内存。这通常表明 c# 中的其他内存已损坏(访问冲突)【英文标题】:Attempted to read or write protected memory. This is often an indication that other memory is corrupt in c# (Access violation) 【发布时间】:2013-05-16 00:14:12 【问题描述】:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int DecompressMCX(object hComp,ref byte[] @in, uint @in_len, ref byte[] @out, ref uint out_len, bool eod);

public class XceedCompressor


    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);       

    byte[] OutRec = new byte[1024 * 100];
    uint outlen;
    DecompressMCX DecompressDelegate;
    int b ;
    unsafe int l;

    public XceedCompressor()
    
        IntPtr pDll = LoadLibrary(@"xceedzip.dll");
        IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "XcUncompress");
        DecompressDelegate = (DecompressMCX)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(DecompressMCX));
    

    public byte[] Decompress(byte[] InRecArr)
    
        outlen = 0;
        l = DecompressDelegate(b, ref InRecArr, (uint)InRecArr.Length, ref OutRec, ref outlen, true);
        return OutRec;
    

这是我要解压的班级。

XceedCompressor xcd = new XceedCompressor ();
xcd.Decompress(some data already compressed with the same library);

但它给出的错误是“尝试读取或写入受保护的内存。这通常表明其他内存已损坏。”

http://doc.xceedsoft.com/products/Xceedzip/Uncompress_method.html

是我想要调用的函数。 希望得到最好的解决方案,就像我在这里总能找到的那样。提前致谢。

【问题讨论】:

我对声明为ref的这些数组持怀疑态度。 是的,数组是问题所在。请注意,我无法理解本机函数的文档。 但是解决方案是什么,因为我应该怎么做到这一点???? 使用 Xceed ZIP 库最简单的方法是使用他们的 .net 组件。试图 p/invoke 本机版本只是受虐狂。更重要的是,你为什么要使用这个库而不是原生的 .net 库?例如,System.IO.Compression.ZipArchive 因为我想解压缩证券交易所之一的实时多播数据字节,其 API 说使用 xceedzip 解压缩。而且作为一个小项目,购买这么昂贵的.net组件对我来说是不可能的。 【参考方案1】:

您不使用 Xceed 的 CSharp Lib 或替代 Zip 库的任何原因? 您应该将您的委托定义为

public delegate int DecompressMCX(int hComp,IntPtr in, uint in_len, IntPtr out, ref uint out_len, bool eod);

在生成inIntPtr 时,修复它很重要,这样垃圾收集器就不会在压缩运行时移动输入数据。

【讨论】:

因为我想解压缩证券交易所之一的实时多播数据字节,其 API 说使用 xceedzip 解压缩。而且作为一个小项目,购买这么昂贵的.net组件对我来说是不可能的。 谢谢,您的解决方案更改委托已删除上述错误,但仍未实现解压。 我希望 xceedzip 基本上是 zlib。您还可以尝试将 .NET 框架类用于流 (IO.Streams)。哪个交易所提供了如此奇怪的建议。 如何修复 IntPtr? @Meekohi docs.microsoft.com/en-us/dotnet/csharp/language-reference/…

以上是关于尝试读取或写入受保护的内存。这通常表明 c# 中的其他内存已损坏(访问冲突)的主要内容,如果未能解决你的问题,请参考以下文章

“试图读取或写入受保护的内存。这通常表明其他内存已损坏” DllImporting C#

Visual Studio C# 试图读取或写入受保护的内存。这通常表明其他内存已损坏

C++ DLL 到 C# 错误:“试图读取或写入受保护的内存。这通常表明其他内存已损坏。”

尝试读取或写入受保护的内存。这通常表明其他内存已损坏

尝试读取或写入受保护的内存。这通常表明其他内存已损坏。在 C++ DLL 中

尝试读取或写入受保护的内存。这通常表明其他内存已损坏