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++的指针,然后操作这两个指针所指向的内容。

解决方案 »

  1.   

    copy代码搞错了,应该是这样:                fixed (byte* pCompress = data, pFile = fileData)
                    {
                        CheckMem(pFile, nFileLen, pCompress, nFileLen + 100);//pCompress无法读写
                        nCompress = Compress2(pFile, nFileLen, pCompress);//pCompress无法读写
                    }
      

  2.   

    郁闷,发现不是fixed问题,这么写同样有问题。    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, nFileLen, pCompress, nFileLen + 100);
        }
      

  3.   

    问题解决,自己搞定,指针要放前面,不能乱放,COM限制了的。    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);
        }