C# - 将String数组转换为sbyte **(String []转换为sbyte **)

时间:2015-06-06 06:06:43

标签: c# arrays pointers clr command-line-interface

XFunction是托管C ++代码(包装器)的CLI。 我想在我的C#Project中使用XFunction(int,sbyte**)并将String数组转换为sbyte **。

sbyte[][] sbytes = new sbyte[7][];
for (int argCounter = 0; argCounter < 7 ; argCounter++)
{   
     //get the byte array
     byte[] bytes = Encoding.ASCII.GetBytes(argument[argCounter]);
    //convert it to sbyte array
    sbytes[argCounter] = new sbyte[bytes.Length];
    for (int i = 0; i < bytes.Length; i++)
    sbytes[argCounter][i] = (sbyte)bytes[i];
}

我打电话的时候:

XFunction(7,sbytes);

和buid,生成此错误:

  

最佳重载方法匹配&#39; XFunction(int,sbyte **)&#39;具有   一些无效的参数参数2:无法转换为&#39; sbyte [] []&#39;   到&#39; sbyte **&#39;

如何修复此错误???

2 个答案:

答案 0 :(得分:0)

您需要使用fixed来获取指向数组的指针,并防止垃圾收集重定位您的变量。

您可能想要这样做:

public static unsafe void CallXFunction(int a, sbyte[][] array)
{
    var pointerArray = new sbyte*[array.Length];

    // Recursive fixing so that whole array get's pinned at same time   
    // (never use fixed pointer outside of fixed{} statement)
    Action<int> fixArray = null;   
    fixArray = (pos) =>
    {
        fixed (sbyte* ptr = array[pos])
        {
            pointerArray[pos] = ptr;

            if (pos <= (array.Length - 2))
            {
                fixArray(pos + 1);
            }
            else
            {
                fixed (sbyte** pointer = pointerArray)
                {
                    XFunction(a, pointer);
                }
            }
        }
    };

    fixArray(0);
}

答案 1 :(得分:0)

它解决了:

            sbyte[][] sbytes = new sbyte[6][];
            for (int argCounter = 0; argCounter < 6 ; argCounter++)
            {   
                get the byte array
                byte[] bytes = Encoding.ASCII.GetBytes(argument[argCounter]);
                convert it to sbyte array1
                sbytes[argCounter] = new sbyte[bytes.Length];
                for (int i = 0; i < bytes.Length; i++)
                    sbytes[argCounter][i] = (sbyte)bytes[i];
            }
            unsafe
            {
                fixed (sbyte* junk = &sbytes[0][0])
                {
                    sbyte*[] arrayofptr = new sbyte*[sbytes.Length];
                    for (int i = 0; i < sbytes.Length; i++)
                    {
                        fixed (sbyte* ptr = &sbytes[i][0])
                        {
                            arrayofptr[i] = ptr;
                        }
                    }
                    fixed (sbyte** ptrptr = &arrayofptr[0])
                    {
                        XFunction(7, ptrptr);                            
                    }
                }
            }