(Примечание: в этом обсуждении рассказывается о том, как работает взаимодействие массивов, что может быть актуально.)
Я пытаюсь передать массив шортов в TypeScript из Blazor, используя оптимизацию взаимодействия Blazor Byte-array.
У меня есть следующий метод C#, который я вызываю из JavaScript:
Код: Выделить всё
[JSInvokable]
public byte[] ReadDataBytes()
{
var shortArray = new short[1000]; // In real use, this comes from some data source.
var byteArray = new byte[shortArray.Length * sizeof(short)];
Buffer.BlockCopy(shortArray, 0, byteArray, 0, byteArray.Length);
return byteArray;
}
Код: Выделить всё
async readData(): Promise
{
const byteArray = await this._dotNetObject.invokeMethodAsync("ReadDataBytes");
console.log("byteOffset = ", byteArray.byteOffset);
// Check if the byteArray is properly aligned for Int16Array
if (byteArray.byteOffset % 2 !== 0)
{
// If not aligned, create a new properly aligned buffer
const alignedBuffer = new ArrayBuffer(byteArray.byteLength);
const alignedView = new Uint8Array(alignedBuffer);
alignedView.set(byteArray);
return new Int16Array(alignedBuffer);
}
// Convert byte array directly to Int16Array (little-endian) if properly aligned
return new Int16Array(byteArray.buffer, byteArray.byteOffset, byteArray.byteLength / 2);
}
Код: Выделить всё
_dotNetObjectКод: Выделить всё
export declare namespace DotNet {
interface DotNetObject {
invokeMethodAsync(methodIdentifier: string, ...args: any[]): Promise;
invokeMethod(methodIdentifier: string, ...args: any[]): T;
dispose(): void;
}
}
Код: Выделить всё
7 byteOffset = 29
7 byteOffset = 30
119 byteOffset = 31
Код: Выделить всё
async readData(): Promise
{
const byteArray = await this._dotNetObject.invokeMethodAsync("ReadDataBytes");
console.log("byteOffset = ", byteArray.byteOffset);
// Convert byte array directly to Int16Array (little-endian)
return new Int16Array(byteArray.buffer, byteArray.byteOffset, byteArray.byteLength / 2);
}
Есть ли способ настроить так, чтобы данные были правильно выровнены по кратному sizeof(short) в ReadDataBytes(), чтобы мне не нужно было копировать данные для их выравнивания в readData()?
Подробнее здесь: https://stackoverflow.com/questions/798 ... terop-to-a
Мобильная версия