如何在js里调用c#函数
时间: 2023-12-30 18:02:16 浏览: 28
要在 JavaScript 中调用 C# 函数,需要使用 WebAssembly 技术。以下是简要的步骤:
1.在 C# 中编写需要被调用的函数,并将其编译为 WebAssembly 模块。
2.在 JavaScript 中加载 WebAssembly 模块,并通过调用模块中的函数来实现与 C# 的交互。
3.在 JavaScript 中使用 fetch() 函数将 WebAssembly 模块加载到浏览器中。
4.在 JavaScript 中使用 WebAssembly.instantiateStreaming() 函数实例化模块。
5.使用模块实例对象中的 exports 属性来调用 C# 函数。
下面是一个简单的示例代码:
// C# 代码
using System;
using System.Runtime.InteropServices;
public static class Example {
[DllImport("example.dll")]
public static extern int Add(int a, int b);
}
// JavaScript 代码
fetch('example.wasm')
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes))
.then(results => {
const module = results.instance;
const addFunction = module.exports._Z3Addii; // 函数名需要根据 C# 编译器生成的名称进行调整
const result = addFunction(1, 2);
console.log(result);
});