简体   繁体   English

C#String []到byte [] []

[英]C# String[] to byte[][]

I have a string array I need to convert to byte[][] (to connect Xcode with Unity scripts in C#). 我有一个字符串数组,我需要转换为byte [] [](将Xcode与C#中的Unity脚本连接)。

This is the functions in Xcode: 这是Xcode中的功能:

void doThisC(char** matrix);

And in Unity in C#, this is what I have but I'm not able to make it work: 在C#中的Unity中,这就是我所拥有的,但我无法使其工作:

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. grid数组只有两个项目,因此代码最多只能处理两个字符串。 You don't need the grid array at all. 您根本不需要grid数组。 Also, you don't create the array buffer : 另外,您不创建数组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: 或使用Linq扩展方法:

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. 在当前的实现中,当您调用buffer[i]您将获得一个异常,但是如上所述,您只需对其进行少量更改即可对其进行修复。 Other parts of your code (depending to your encoding), seems correct. 您代码的其他部分(取决于您的编码),似乎是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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