marcg11
marcg11

Reputation: 732

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);     
}

Upvotes: 1

Views: 898

Answers (2)

Guffa
Guffa

Reputation: 700312

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);     
}

Upvotes: 3

Saeed Amiri
Saeed Amiri

Reputation: 22555

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.

Upvotes: 2

Related Questions