0

我正在尝试将我在 Delphi 中的解密函数移植到 C#。在 delphi 中,我使用函数 Move 使用指针将数据放入内存中,因此我尝试使用 marshal.copy 函数获得相同的结果,但有时我会遇到访问冲突异常,有时还会出现空格。附上函数的代码。有任何想法吗?非常感谢!

    public string prDecode(string s)
    {
        byte[] ArrayMap = new byte[256] {0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  
                                         0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59,60,
                                         61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2,  3, 4, 5, 6, 7, 8, 9, 10, 
                                         11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 
                                         0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 
                                         36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
                                         51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
                                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 
        int I;
        char[] ArrayS = s.ToCharArray(0, s.Length);
        string resultado = "";
        char[] ArrayR = resultado.ToCharArray(0, resultado.Length);
        switch (s.Length)
        {
            case 2: 
                I = ArrayMap[ArrayS[0]] + (ArrayMap[ArrayS[1]] << 6);
                ArrayR = new char[1];
                Marshal.Copy((IntPtr)I, ArrayR, 0, ArrayR.Length);

                break;
            case 3:
                I = ArrayMap[ArrayS[0]] + (ArrayMap[ArrayS[1]] << 6) + 
                    (ArrayMap[ArrayS[2]] << 12);
                ArrayR = new char[2];
                Marshal.Copy((IntPtr)I, ArrayR, 0, ArrayR.Length);
                break;

            case 4:
                I = ArrayMap[ArrayS[0]] + (ArrayMap[ArrayS[1]] << 6) + 
                    (ArrayMap[ArrayS[2]] << 12) + (ArrayMap[ArrayS[3]] << 18);
                ArrayR = new char[3];
                Marshal.Copy((IntPtr)I, ArrayR, 0, ArrayR.Length);
                break;
        }
        string clave = new string (ArrayR);
        return clave;

    }
4

2 回答 2

2

I think the function you're looking for is Array.Copy or Buffer.BlockCopy rather than Marshal.Copy. Marshal.Copy is for copying data to and from unmanaged memory.

于 2012-08-23T14:21:10.810 回答
1

除非您为遗留代码访问非托管内存,否则无需使用 Marshal。托管代码不需要指针,使用托管方法会更快。

我认为您正在寻找的是使用托管代码在数组之间复制的 Array.Copy。

于 2012-08-23T14:20:26.777 回答