You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor与JS互操作:如何返回MemoryView避免数据拷贝?

问题背景(系列第3部分)

我希望找到一种从JavaScript互操作向Blazor返回Task值(或其他指针共享语法)的解决方案,避免数据封送时的拷贝操作。

以下是一个可异步向JavaScript发送MemoryView参数,但无法接收返回MemoryView的示例(基于Mister Magoo的示例修改):

导入代码

[JSImport("getMessage", "SampleJS")]
[return: JSMarshalAs<JSType.Promise<JSType.Any>>()]
internal static partial Task<object> 
  GetWelcomeMessage([JSMarshalAs<JSType.MemoryView>] ArraySegment<byte> bytes);

JS模块代码

export async function getMessage(dataPointer) {
  var maskedData = new Uint8Array(dataPointer.slice())
  console.log(maskedData)
  return await new Promise((resolve) => {
    setTimeout(() => {
      resolve(maskedData);
    }, 2000);
  });
}

该示例仅记录接收到的字节数据,等待2秒后返回相同数据。

使用代码

byte[] sampleData = Encoding.UTF8.GetBytes("Hello from C#");
ArraySegment<byte> sampleDataPointer = new ArraySegment<byte>(sampleData);
object? result = await GetWelcomeMessage(sampleDataPointer);
if (result is byte[] bytes)
{
    message = Encoding.UTF8.GetString(bytes);
    Console.WriteLine($"Got {message} from {result.GetType()}");
}

核心问题

如何修改代码,使返回结果无需进行封送拷贝,而是直接返回指针?是否会因JavaScript内存在返回时被释放而导致技术上不可行?


内容的提问来源于stack exchange,提问作者Sean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:51:37