mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-03-31 01:11:06 +00:00
365 lines
30 KiB
HTML
365 lines
30 KiB
HTML
![]() |
<!DOCTYPE HTML>
|
||
|
<html lang="en" class="sidebar-visible no-js">
|
||
|
<head>
|
||
|
<!-- Book generated using mdBook -->
|
||
|
<meta charset="UTF-8">
|
||
|
<title>Exporting a function to JS - The `wasm-bindgen` Guide</title>
|
||
|
|
||
|
|
||
|
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
|
<meta name="description" content="">
|
||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
<meta name="theme-color" content="#ffffff" />
|
||
|
|
||
|
<link rel="shortcut icon" href="../../favicon.png">
|
||
|
<link rel="stylesheet" href="../../css/variables.css">
|
||
|
<link rel="stylesheet" href="../../css/general.css">
|
||
|
<link rel="stylesheet" href="../../css/chrome.css">
|
||
|
<link rel="stylesheet" href="../../css/print.css" media="print">
|
||
|
|
||
|
<!-- Fonts -->
|
||
|
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
|
||
|
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
|
||
|
<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">
|
||
|
|
||
|
<!-- Highlight.js Stylesheets -->
|
||
|
<link rel="stylesheet" href="../../highlight.css">
|
||
|
<link rel="stylesheet" href="../../tomorrow-night.css">
|
||
|
<link rel="stylesheet" href="../../ayu-highlight.css">
|
||
|
|
||
|
<!-- Custom theme stylesheets -->
|
||
|
|
||
|
|
||
|
|
||
|
</head>
|
||
|
<body class="light">
|
||
|
<!-- Provide site root to javascript -->
|
||
|
<script type="text/javascript">
|
||
|
var path_to_root = "../../";
|
||
|
var default_theme = "light";
|
||
|
</script>
|
||
|
|
||
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
||
|
<script type="text/javascript">
|
||
|
try {
|
||
|
var theme = localStorage.getItem('mdbook-theme');
|
||
|
var sidebar = localStorage.getItem('mdbook-sidebar');
|
||
|
|
||
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
||
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
||
|
}
|
||
|
|
||
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
||
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
||
|
}
|
||
|
} catch (e) { }
|
||
|
</script>
|
||
|
|
||
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
|
<script type="text/javascript">
|
||
|
var theme;
|
||
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
||
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
||
|
document.body.className = theme;
|
||
|
document.querySelector('html').className = theme + ' js';
|
||
|
</script>
|
||
|
|
||
|
<!-- Hide / unhide sidebar before it is displayed -->
|
||
|
<script type="text/javascript">
|
||
|
var html = document.querySelector('html');
|
||
|
var sidebar = 'hidden';
|
||
|
if (document.body.clientWidth >= 1080) {
|
||
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
||
|
sidebar = sidebar || 'visible';
|
||
|
}
|
||
|
html.classList.remove('sidebar-visible');
|
||
|
html.classList.add("sidebar-" + sidebar);
|
||
|
</script>
|
||
|
|
||
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
||
|
<div class="sidebar-scrollbox">
|
||
|
<ol class="chapter"><li class="affix"><a href="../../introduction.html">Introduction</a></li><li class="spacer"></li><li><a href="../../examples/index.html"><strong aria-hidden="true">1.</strong> Examples</a></li><li><ol class="section"><li><a href="../../examples/hello-world.html"><strong aria-hidden="true">1.1.</strong> Hello, World!</a></li><li><a href="../../examples/console-log.html"><strong aria-hidden="true">1.2.</strong> Using console.log</a></li><li><a href="../../examples/add.html"><strong aria-hidden="true">1.3.</strong> Small wasm files</a></li><li><a href="../../examples/without-a-bundler.html"><strong aria-hidden="true">1.4.</strong> Without a Bundler</a></li><li><a href="../../examples/wasm2js.html"><strong aria-hidden="true">1.5.</strong> Converting WebAssembly to JS</a></li><li><a href="../../examples/import-js.html"><strong aria-hidden="true">1.6.</strong> Importing functions from JS</a></li><li><a href="../../examples/char.html"><strong aria-hidden="true">1.7.</strong> Working with char</a></li><li><a href="../../examples/wasm-in-wasm.html"><strong aria-hidden="true">1.8.</strong> js-sys: WebAssembly in WebAssembly</a></li><li><a href="../../examples/dom.html"><strong aria-hidden="true">1.9.</strong> web-sys: DOM hello world</a></li><li><a href="../../examples/closures.html"><strong aria-hidden="true">1.10.</strong> web-sys: Closures</a></li><li><a href="../../examples/performance.html"><strong aria-hidden="true">1.11.</strong> web-sys: performance.now</a></li><li><a href="../../examples/fetch.html"><strong aria-hidden="true">1.12.</strong> web-sys: using fetch</a></li><li><a href="../../examples/2d-canvas.html"><strong aria-hidden="true">1.13.</strong> web-sys: canvas hello world</a></li><li><a href="../../examples/julia.html"><strong aria-hidden="true">1.14.</strong> web-sys: canvas Julia set</a></li><li><a href="../../examples/web-audio.html"><strong aria-hidden="true">1.15.</strong> web-sys: WebAudio</a></li><li><a href="../../examples/webgl.html"><strong aria-hidden="true">1.16.</strong> web-sys: WebGL</a></li><li><a href="../../examples/websockets.html"><strong aria-hidden="true">1.17.</strong> web-sys: WebSockets</a></li><li><a href="../../examples/webrtc_datachannel.html"><strong aria-hidden="true">1.18.</strong> web-sys: WebRTC DataChannel</a></li><li><a href="../../examples/request-animation-frame.html"><strong aria-hidden="true">1.19.</strong> web-sys: requestAnimationFrame</a></li><li><a href="../../examples/paint.html"><strong aria-hidden="true">1.20.</strong> web-sys: A Simple Paint Program</a></li><li><a href="../../examples/raytrace.html"><strong aria-hidden="true">1.21.</strong> Parallel Raytracing</a></li><li><a href="../../examples/todomvc.html"><strong aria-hidden="true">1.22.</strong> web-sys: A TODO MVC App</a></li></ol></li><li><a href="../../reference/index.html"><strong aria-hidden="true">2.</strong> Reference</a></li><li><ol class="section"><li><a href="../../reference/deployment.html"><strong aria-hidden="true">2.1.</strong> Deployment</a></li><li><a href="../../reference/js-snippets.html"><strong aria-hidden="true">2.2.</strong> JS snippets</a></li><li><a href="../../reference/passing-rust-closures-to-js.html"><strong aria-hidden="true">2.3.</strong> Passing Rust Closures to JS</a></li><li><a href="../../reference/receiving-js-closures-in-rust.html"><strong aria-hidden="true">2.4.</strong> Receiving JS Closures in Rust</a></li><li><a href="../../reference/js-promises-and-rust-futures.html"><strong aria-hidden="true">2.5.</strong> Promises and Futures</a></li><li><a href="../../reference/iterating-over-js-values.html"><strong aria-hidden="true">2.6.</strong> Iterating over JS Values</a></li><li><a href="../../reference/arbitrary-data-with-serde.html"><strong aria-hidden="true">2.7.</strong> Arbitrary Data with Serde</a></li><li><a href="../../reference/accessing-properties-of-untyped-js-values.html"><strong aria-hidden="true">2.8.</strong> Accessing Properties of Untyped JS Values</a></li><li><a href="../../reference/working-with-duck-typed-interfaces.html"><
|
||
|
</div>
|
||
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
|
||
|
</nav>
|
||
|
|
||
|
<div id="page-wrapper" class="page-wrapper">
|
||
|
|
||
|
<div class="page">
|
||
|
<style>
|
||
|
header.warning {
|
||
|
background-color: rgb(242, 222, 222);
|
||
|
border-bottom-color: rgb(238, 211, 215);
|
||
|
border-bottom-left-radius: 4px;
|
||
|
border-bottom-right-radius: 4px;
|
||
|
border-bottom-style: solid;
|
||
|
border-bottom-width: 0.666667px;
|
||
|
border-image-outset: 0 0 0 0;
|
||
|
border-image-repeat: stretch stretch;
|
||
|
border-image-slice: 100% 100% 100% 100%;
|
||
|
border-image-source: none;
|
||
|
border-image-width: 1 1 1 1;
|
||
|
border-left-color: rgb(238, 211, 215);
|
||
|
border-left-style: solid;
|
||
|
border-left-width: 0.666667px;
|
||
|
border-right-color: rgb(238, 211, 215);
|
||
|
border-right-style: solid;
|
||
|
border-right-width: 0.666667px;
|
||
|
border-top-color: rgb(238, 211, 215);
|
||
|
border-top-left-radius: 4px;
|
||
|
border-top-right-radius: 4px;
|
||
|
border-top-style: solid;
|
||
|
border-top-width: 0.666667px;
|
||
|
color: rgb(185, 74, 72);
|
||
|
margin-bottom: 0px;
|
||
|
margin-left: 0px;
|
||
|
margin-right: 0px;
|
||
|
margin-top: 30px;
|
||
|
padding-bottom: 8px;
|
||
|
padding-left: 14px;
|
||
|
padding-right: 35px;
|
||
|
padding-top: 8px;
|
||
|
text-align: center;
|
||
|
}
|
||
|
</style>
|
||
|
<header class='warning'>
|
||
|
This is the <strong>unpublished</strong> documentation of
|
||
|
<code>wasm-bindgen</code>, the published documentation is available
|
||
|
<a href="https://rustwasm.github.io/docs/wasm-bindgen/">
|
||
|
on the main Rust and WebAssembly documentation site
|
||
|
</a>. Features documented here may not be available in released versions of
|
||
|
<code>wasm-bindgen</code>.
|
||
|
</header>
|
||
|
|
||
|
<div id="menu-bar" class="menu-bar">
|
||
|
<div id="menu-bar-sticky-container">
|
||
|
<div class="left-buttons">
|
||
|
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
||
|
<i class="fa fa-bars"></i>
|
||
|
</button>
|
||
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
||
|
<i class="fa fa-paint-brush"></i>
|
||
|
</button>
|
||
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
||
|
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
|
||
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
||
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
||
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
||
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
||
|
</ul>
|
||
|
|
||
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
||
|
<i class="fa fa-search"></i>
|
||
|
</button>
|
||
|
|
||
|
</div>
|
||
|
|
||
|
<h1 class="menu-title">The `wasm-bindgen` Guide</h1>
|
||
|
|
||
|
<div class="right-buttons">
|
||
|
<a href="../../print.html" title="Print this book" aria-label="Print this book">
|
||
|
<i id="print-button" class="fa fa-print"></i>
|
||
|
</a>
|
||
|
|
||
|
</div>
|
||
|
</div>
|
||
|
</div>
|
||
|
|
||
|
|
||
|
<div id="search-wrapper" class="hidden">
|
||
|
<form id="searchbar-outer" class="searchbar-outer">
|
||
|
<input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
||
|
</form>
|
||
|
<div id="searchresults-outer" class="searchresults-outer hidden">
|
||
|
<div id="searchresults-header" class="searchresults-header"></div>
|
||
|
<ul id="searchresults">
|
||
|
</ul>
|
||
|
</div>
|
||
|
</div>
|
||
|
|
||
|
|
||
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
||
|
<script type="text/javascript">
|
||
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
||
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
||
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
||
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
||
|
});
|
||
|
</script>
|
||
|
|
||
|
<div id="content" class="content">
|
||
|
<main>
|
||
|
<h1><a class="header" href="#exporting-a-function-to-js" id="exporting-a-function-to-js">Exporting a function to JS</a></h1>
|
||
|
<p>Alright now that we've got a good grasp on JS objects and how they're working,
|
||
|
let's take a look at another feature of <code>wasm-bindgen</code>: exporting functionality
|
||
|
with types that are richer than just numbers.</p>
|
||
|
<p>The basic idea around exporting functionality with more flavorful types is that
|
||
|
the wasm exports won't actually be called directly. Instead the generated
|
||
|
<code>foo.js</code> module will have shims for all exported functions in the wasm module.</p>
|
||
|
<p>The most interesting conversion here happens with strings so let's take a look
|
||
|
at that.</p>
|
||
|
<pre><pre class="playpen"><code class="language-rust">
|
||
|
# #![allow(unused_variables)]
|
||
|
#fn main() {
|
||
|
#[wasm_bindgen]
|
||
|
pub fn greet(a: &str) -> String {
|
||
|
format!("Hello, {}!", a)
|
||
|
}
|
||
|
#}</code></pre></pre>
|
||
|
<p>Here we'd like to define an ES module that looks like</p>
|
||
|
<pre><code class="language-ts">// foo.d.ts
|
||
|
export function greet(a: string): string;
|
||
|
</code></pre>
|
||
|
<p>To see what's going on, let's take a look at the generated shim</p>
|
||
|
<pre><code class="language-js">import * as wasm from './foo_bg';
|
||
|
|
||
|
function passStringToWasm(arg) {
|
||
|
const buf = new TextEncoder('utf-8').encode(arg);
|
||
|
const len = buf.length;
|
||
|
const ptr = wasm.__wbindgen_malloc(len);
|
||
|
let array = new Uint8Array(wasm.memory.buffer);
|
||
|
array.set(buf, ptr);
|
||
|
return [ptr, len];
|
||
|
}
|
||
|
|
||
|
function getStringFromWasm(ptr, len) {
|
||
|
const mem = new Uint8Array(wasm.memory.buffer);
|
||
|
const slice = mem.slice(ptr, ptr + len);
|
||
|
const ret = new TextDecoder('utf-8').decode(slice);
|
||
|
return ret;
|
||
|
}
|
||
|
|
||
|
export function greet(arg0) {
|
||
|
const [ptr0, len0] = passStringToWasm(arg0);
|
||
|
try {
|
||
|
const ret = wasm.greet(ptr0, len0);
|
||
|
const ptr = wasm.__wbindgen_boxed_str_ptr(ret);
|
||
|
const len = wasm.__wbindgen_boxed_str_len(ret);
|
||
|
const realRet = getStringFromWasm(ptr, len);
|
||
|
wasm.__wbindgen_boxed_str_free(ret);
|
||
|
return realRet;
|
||
|
} finally {
|
||
|
wasm.__wbindgen_free(ptr0, len0);
|
||
|
}
|
||
|
}
|
||
|
</code></pre>
|
||
|
<p>Phew, that's quite a lot! We can sort of see though if we look closely what's
|
||
|
happening:</p>
|
||
|
<ul>
|
||
|
<li>
|
||
|
<p>Strings are passed to wasm via two arguments, a pointer and a length. Right
|
||
|
now we have to copy the string onto the wasm heap which means we'll be using
|
||
|
<code>TextEncoder</code> to actually do the encoding. Once this is done we use an
|
||
|
internal function in <code>wasm-bindgen</code> to allocate space for the string to go,
|
||
|
and then we'll pass that ptr/length to wasm later on.</p>
|
||
|
</li>
|
||
|
<li>
|
||
|
<p>Returning strings from wasm is a little tricky as we need to return a ptr/len
|
||
|
pair, but wasm currently only supports one return value (multiple return values
|
||
|
<a href="https://github.com/WebAssembly/design/issues/1146">is being standardized</a>).
|
||
|
To work around this in the meantime, we're actually returning a pointer to a
|
||
|
ptr/len pair, and then using functions to access the various fields.</p>
|
||
|
</li>
|
||
|
<li>
|
||
|
<p>Some cleanup ends up happening in wasm. The <code>__wbindgen_boxed_str_free</code>
|
||
|
function is used to free the return value of <code>greet</code> after it's been decoded
|
||
|
onto the JS heap (using <code>TextDecoder</code>). The <code>__wbindgen_free</code> is then used to
|
||
|
free the space we allocated to pass the string argument once the function call
|
||
|
is done.</p>
|
||
|
</li>
|
||
|
</ul>
|
||
|
<p>Next let's take a look at the Rust side of things as well. Here we'll be looking
|
||
|
at a mostly abbreviated and/or "simplified" in the sense of this is what it
|
||
|
compiles down to:</p>
|
||
|
<pre><pre class="playpen"><code class="language-rust">
|
||
|
# #![allow(unused_variables)]
|
||
|
#fn main() {
|
||
|
pub extern "C" fn greet(a: &str) -> String {
|
||
|
format!("Hello, {}!", a)
|
||
|
}
|
||
|
|
||
|
#[export_name = "greet"]
|
||
|
pub extern "C" fn __wasm_bindgen_generated_greet(
|
||
|
arg0_ptr: *const u8,
|
||
|
arg0_len: usize,
|
||
|
) -> *mut String {
|
||
|
let arg0 = unsafe {
|
||
|
let slice = ::std::slice::from_raw_parts(arg0_ptr, arg0_len);
|
||
|
::std::str::from_utf8_unchecked(slice)
|
||
|
};
|
||
|
let _ret = greet(arg0);
|
||
|
Box::into_raw(Box::new(_ret))
|
||
|
}
|
||
|
#}</code></pre></pre>
|
||
|
<p>Here we can see again that our <code>greet</code> function is unmodified and has a wrapper
|
||
|
to call it. This wrapper will take the ptr/len argument and convert it to a
|
||
|
string slice, while the return value is boxed up into just a pointer and is
|
||
|
then returned up to was for reading via the <code>__wbindgen_boxed_str_*</code> functions.</p>
|
||
|
<p>So in general exporting a function involves a shim both in JS and in Rust with
|
||
|
each side translating to or from wasm arguments to the native types of each
|
||
|
language. The <code>wasm-bindgen</code> tool manages hooking up all these shims while the
|
||
|
<code>#[wasm_bindgen]</code> macro takes care of the Rust shim as well.</p>
|
||
|
<p>Most arguments have a relatively clear way to convert them, bit if you've got
|
||
|
any questions just let me know!</p>
|
||
|
|
||
|
</main>
|
||
|
|
||
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
||
|
<!-- Mobile navigation buttons -->
|
||
|
|
||
|
<a rel="prev" href="../../contributing/design/js-objects-in-rust.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
|
<i class="fa fa-angle-left"></i>
|
||
|
</a>
|
||
|
|
||
|
|
||
|
|
||
|
<a rel="next" href="../../contributing/design/exporting-rust-struct.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
|
<i class="fa fa-angle-right"></i>
|
||
|
</a>
|
||
|
|
||
|
|
||
|
<div style="clear: both"></div>
|
||
|
</nav>
|
||
|
</div>
|
||
|
</div>
|
||
|
|
||
|
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
||
|
|
||
|
<a href="../../contributing/design/js-objects-in-rust.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
|
<i class="fa fa-angle-left"></i>
|
||
|
</a>
|
||
|
|
||
|
|
||
|
|
||
|
<a href="../../contributing/design/exporting-rust-struct.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
|
<i class="fa fa-angle-right"></i>
|
||
|
</a>
|
||
|
|
||
|
</nav>
|
||
|
|
||
|
</div>
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
<script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
|
||
|
<script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
|
||
|
<script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>
|
||
|
|
||
|
|
||
|
<script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
|
||
|
<script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
|
||
|
<script src="../../book.js" type="text/javascript" charset="utf-8"></script>
|
||
|
|
||
|
<!-- Custom JS scripts -->
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
</body>
|
||
|
</html>
|