我从串行通信中获取二进制数据,我需要将其编组到C#托管结构中。一切正常。
其中一个回复是一系列结构,我按照以下方式进行编组:
socket$: WebSocketSubject<any>;
constructor() {
this.socket$ = WebSocketSubject.create(SOCKET_URL);
this.socket$.subscribe(
(message) => console.log('<-- ' + message),
(err) => console.error('Error on WebSocket:', err),
() => console.warn('Completed!')
);
}
send(message: SocketMessage) {
const tmp: any = {};
tmp.type = message.type;
tmp.payload = message.payload;
// This will be received by the server but also by client subscriptions = bad
this.socket$.next(JSON.stringify(tmp));
}
没有循环可以实现这个目标吗?我已经在MSDN中浏览了这里,但是却没有找到任何可以取代byte[] buffer = /* binary data from serial port */
int sizeOfElement = Marshal.SizeOf(element);
IntPtr ptr = Marshal.AllocHGlobal(sizeOfElement);
int numElements = buffer.Length / sizeOfElement;
TItem[] array = new TItem[numElements]; //TItem is a generic type
for (int i = 0; i < numElements; i++)
{
int offset = (sizeOfElement * i);
Marshal.Copy(this.Content, offset, ptr, sizeOfElement);
array[i] = (TItem)Marshal.PtrToStructure(ptr, typeof(TItem));
Marshal.DestroyStructure(ptr, typeof(TItem));
}
Marshal.FreeHGlobal(ptr);
调用的内容,而是使用整个缓冲区。
提前致谢!