Movatterモバイル変換


[0]ホーム

URL:


  1. WebAssembly
  2. Reference
  3. WebAssembly types
  4. funcref

funcref: Wasm type

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since November 2021.

Thefuncref value type references a function defined in Wasm, enabling higher-order functions to be used across the Wasm and JavaScript language boundaries.

Try it

(module  ;; Import forEach() function, which takes an externref and a funcref as params  (import "js" "forEach" (func $forEach (param externref) (param funcref)))  ;; Define double() function, which doubles a value, and returns the result  (func $double (export "double") (param f64) (result f64)    (f64.mul (local.get 0) (f64.const 2))  )  ;; Export doubleArray() function, which takes an externref param, then  ;; calls the forEach() function, passing it the externref and the double()  ;; function as params  (func (export "doubleArray")    (param $arr externref)    (call $forEach      (local.get $arr)      (ref.func $double)    )  ))
// Define an array of numbersconst arr = [1, 4, 9, 16, 64];// Define a forEach function, which runs a callback function on each element of an arrayconst importObj = {  js: {    forEach(array, callback) {      array.forEach((value) => {        const result = callback(value);        console.log(result);      });    },  },};// Compile and instantiate the wasm module, importing the importObj namespace// in the processWebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), importObj).then(  ({ instance }) => {    // Run the exported doubleArray() function, passing it our array    instance.exports.doubleArray(arr);  },);

Syntax

wat
;; Define imported function callback parameter(param funcref)

Description

Thefuncref type is used to create a reference to a function created in Wasm, which can then be passed into a function imported from JavaScript. A typical use of this is to enable Wasm functions to be passed into JavaScript functions as callbacks.

Examples

Basicfuncref usage

In this example, we import a custom JavaScriptmap() function into a Wasm module, which accepts an array and a callback function as parameters. The callback function parameter is given a funcref type, meaning it can then be defined inside Wasm and passed into the JavaScript function.

JavaScript

First of all, we grab references to a<p> element, which we will output our results into, and an array, which we will later pass into an exported WebAssembly function call.

<p></p>
js
const output = document.querySelector("p");const arr = [1, 4, 9, 16, 64];

Next, we create an import object and define a function calledmap() inside it, which takes two parameters, an array and a callback function. Inside, we create a new array (result) by passing every value inside the array into the callback function via the built-in JavaScriptArray.map() function. Finally, we set the result as the value of the output element'stextContent.

js
const importObj = {  js: {    map(array, callback) {      const result = array.map((value) => callback(value));      output.textContent = result;    },  },};

The last step in our JavaScript is to compile and instantiate the Wasm module usingWebAssembly.instantiateStreaming(), importing theimportObj namespace in the process. When the result is returned, we invoke the WasmdoubleArray() function available on the WebAssemblyInstanceexports object, passing it thearr array as a parameter.

js
WebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), importObj).then(  ({ instance }) => {    instance.exports.doubleArray(arr);  },);

Wasm

In our Wasm module, we first import themap() function from the importedjs namespace, giving it a reference name of$map. The firstparam is given anexternref type (which represents the array parameter), and the second is given afuncref type (which represents the callback parameter).

Next, we define a function calleddouble(), which both takes and returns a floating point number parameter. The function body multiplies the parameter by 2, using themul instruction.

Finally, we define the exporteddoubleArray() function. Its has a single definedparam$arr — with anexternref type, which makes sense, as we are calling it from JavaScript and providing the value there. Inside, we call the importedmap() function, passing it the$arrexternref and thedouble() function as its parameters.

wat
(module  (import "js" "map" (func $map (param externref) (param funcref)))  (func $double (export "double") (param f64) (result f64)    (f64.mul (local.get 0) (f64.const 2))  )  (func (export "doubleArray")    (param $arr externref)    (call $map      (local.get $arr)      (ref.func $double)    )  ))

Result

The rendered output looks like this:

The original array has all its values multiplied by2, and the resulting new array is output in our<p> element. This makes sense: We call the exporteddoubleArray() function from JavaScript. The Wasm module then handles calling our JavaScriptmap() function, passing it the array and the Wasm-defineddouble() callback function so it can apply the callback to each array value viaArray.map().

Specifications

Specification
Unknown specification
# reference-types

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp