我们知道,VC里的二维数据是连续存放的,可以直接将整个buffer发送给通讯的远端。
但是C#是变长数组,特别是二维数组,需要转换成一维byte[]则相当困难了。
经过研究,得到了如下的代码,并测试通过!
byte[] Array2Bytes(int[,] array) { byte[] bytes = new byte[4 * array.GetLength(0) * array.GetLength(1)]; int n = 0; for (int i = 0; i < array.GetLength(0); i++) for (int j = 0; j < array.GetLength(1); j++) { byte[] byInt = BitConverter.GetBytes(array[i, j]); for (int k = 0; k < 4; k++) { bytes[n++] = byInt[k]; } } return bytes; } private void Form1_Load(object sender, EventArgs e) { int[,] arrInt = new int[3, 4]; for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) { arrInt[i, j] = (i + 1) * (j + 1); } byte[] bytes = Array2Bytes(arrInt); File.WriteAllBytes("d:\\test.bin", bytes); }
接收端C++端测试代码如下
#include <stdio.h> int _tmain(int argc, _TCHAR* argv[]) { FILE *fp = fopen("d:\\test.bin","rb"); int arr[3][4]; fread( arr,3*4*4,1,fp); for(int i=0;i<3;i++) for(int j=0;j<4;j++) { //ASSERT( (i+1)*(j+1)==arr[i][j] ); } return 0; }