日期:2014-05-18  浏览次数:20976 次

关于fixed关键字的奇怪问题
C# code
            unsafe
            {
                // read file to buffer and close the file.
                FileStream sFile = new FileStream("d:\\Microsoft C Program.doc", FileMode.Open);
                long nFileLen = sFile.Length;
                byte[] fileData = new byte[nFileLen];
                sFile.Read(fileData, 0, (int)nFileLen);
                sFile.Close();
                // allocate buffer for compressing
                int nCompress = 0;
                byte[] data = new byte[nFileLen+100];
                fixed (byte* pCompress = data, pFile = &fileData)
                {
                    CheckMem(pFile, nFileLen, pCompress, nFileLen + 100);//pCompress访问出错
                    nCompress = Compress2(pFile, nFileLen, pCompress);

                }
            }


CheckMem和Compress2是C++写的dll导出函数,关于如何调用C++动态库基本上没问题。现在的问题是:
1、如果使用fixed关键字的时候似乎只能fixed一个byte*,无论读写内存都不会有问题。
2、如果使用fixed关键字fixed两个byte*的话,总会有一个byte*所指向的内存无法读写。

请问这是什么原因?如果无法避免这个问题,怎么绕过?我想要的结果就是取得两个类似于C++的指针,然后操作这两个指针所指向的内容。

------解决方案--------------------
问题解决,自己搞定,指针要放前面,不能乱放,COM限制了的。
C# code

    unsafe
    {
    // read file to buffer and close the file.
    FileStream sFile = new FileStream("d:\\Microsoft C Program.doc", FileMode.Open);
    long nFileLen = sFile.Length;
    byte[] fileData = new byte[nFileLen];
    sFile.Read(fileData, 0, (int)nFileLen);
    sFile.Close();
    IntPtr pData = Marshal.AllocHGlobal((int)nFileLen);
    Marshal.Copy(fileData, 0, pData, (int)nFileLen);

    int nCompress = 0;
    // allocate buffer for compressing
    IntPtr pCompress = Marshal.AllocHGlobal((int)(nFileLen+100));

    CheckMem(pData, pCompress, nFileLen, nFileLen+100);
    }