简体   繁体   中英

C# String[] to byte[][]

I have a string array I need to convert to byte[][] (to connect Xcode with Unity scripts in C#).

This is the functions in Xcode:

void doThisC(char** matrix);

And in Unity in C#, this is what I have but I'm not able to make it work:

public static void doThis(string[] array, int size){
    char[][] grid = new char[][] { new char[size] , new char[100]}; 
    byte[][] buffer;

   for(int i = 0 ; i < size ; i++)
   {
      grid[i] = array[i].ToString().ToCharArray();
      buffer[i] = (new System.Text.UTF8Encoding()).GetBytes(grid[i]);
   }
   doThisC(buffer);     
}

The grid array only has two items, so the code will only work up to two strings. You don't need the grid array at all. Also, you don't create the array buffer :

public static void doThis(string[] array){
   byte[][] buffer = new byte[array.Length][];
   for(int i = 0 ; i < array.Length ; i++)
   {
      buffer[i] = System.Text.Encoding.UTF8.GetBytes(array[i]);
   }
   doThisC(buffer);     
}

or using Linq extension methods:

public static void doThis(string[] array){
   byte[][] buffer = array.Select(System.Text.Encoding.UTF8.GetBytes).ToArray();
   doThisC(buffer);     
}

I think your problem is just with array creation, you should first create a byte array properly:

byte[][] buffer = new byte[size][];

In your current implementation, when you call buffer[i] you will get an exception, but you can fix it with little change as mentioned above. Other parts of your code (depending to your encoding), seems correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM