Add a .gitattributes file to specify eol=LF (#1370)

* Add a .gitattributes file specifying LF-style line endings.

This is similar to [Rust's .gitattributes file] though simplified.
Most of our source and documentation files already used LF-style line
endings, including *.cs files, so this makes things more consistent.

[Rust's .gitattributes file]: https://github.com/rust-lang/rust/blob/master/.gitattributes

* Remove UTF-8 BOMs in *.cs files.

Most of our *.cs files don't have UTF-8 BOMs, so this makes things more
consistent.
This commit is contained in:
Dan Gohman
2020-03-20 18:36:13 -07:00
committed by GitHub
parent 815e340f85
commit c202a8eeaf
21 changed files with 1164 additions and 1157 deletions

7
.gitattributes vendored Normal file
View File

@@ -0,0 +1,7 @@
# Use LF-style line endings for all text files.
* text=auto eol=lf
# Older git versions try to fix line endings on images, this prevents it.
*.png binary
*.ico binary
*.wasm binary

View File

@@ -1,9 +1,9 @@
###############
# folder #
###############
/**/DROP/
/**/TEMP/
/**/packages/
/**/bin/
/**/obj/
_site
###############
# folder #
###############
/**/DROP/
/**/TEMP/
/**/packages/
/**/bin/
/**/obj/
_site

View File

@@ -1,5 +1,5 @@
###############
# temp file #
###############
*.yml
.manifest
###############
# temp file #
###############
*.yml
.manifest

View File

@@ -1,5 +1,5 @@
# Wasmtime for NET
This is the .NET API for [Wasmtime](https://github.com/bytecodealliance/wasmtime).
# Wasmtime for NET
This is the .NET API for [Wasmtime](https://github.com/bytecodealliance/wasmtime).
See the [documentation](Wasmtime.html#classes) for the various .NET classes.

View File

@@ -1,211 +1,211 @@
# Introduction to Wasmtime for .NET
[Wasmtime](https://github.com/bytecodealliance/wasmtime) is a standalone runtime capable of executing [WebAssembly](https://webassembly.org/) outside of a web browser.
Wasmtime for .NET is a .NET API for Wasmtime. It enables .NET developers to easily instantiate and execute WebAssembly modules.
For this tutorial, we will create a WebAssembly module from a program written in Rust and use that WebAssembly module from a .NET Core 3.0 application.
# Creating a simple WebAssembly module
One of the reasons why WebAssembly is so exciting is that [many languages are able to target WebAssembly](https://github.com/appcypher/awesome-wasm-langs). This means, for example, a plugin model based on WebAssembly could enable developers to write sandboxed, cross-platform plugins in any number of languages.
Here I've decided to use [Rust](https://www.rust-lang.org/) for the implementation of the WebAssembly module. Rust is a modern systems programming language that can easily target WebAssembly.
If you wish to skip creating the WebAssembly module, download the [prebuilt WebAssembly module](https://raw.githubusercontent.com/bytecodealliance/wasmtime/master/crates/misc/dotnet/docs/wasm/intro/hello.wasm) from this tutorial, copy it to your .NET project directory, and continue from the _[Using the WebAssembly module from .NET](#using-the-webassembly-module-from-net)_ section.
## Installing a Rust toolchain
To get started with Rust, install [rustup](https://rustup.rs/), the manager for Rust toolchains.
This will install both a `rustup` command and a `cargo` command (for the active Rust toolchain) to your PATH.
## Installing the WebAssembly target
To target WebAssembly with the active Rust toolchain, install the WebAssembly [target triple](https://forge.rust-lang.org/release/platform-support.html):
```text
rustup target add wasm32-unknown-unknown
```
## Creating the Rust project
Create a new Rust library project named `hello`:
```text
cargo new --lib hello
cd hello
```
To target WebAssembly, the library needs to be built as a `cdylib` (dynamic library) rather than the default of a static Rust library. Add the following to the `Cargo.toml` file in the project root:
```toml
[lib]
crate-type = ["cdylib"]
```
## Implementing the WebAssembly code
The WebAssembly implementation will import a `print` function from the host environment and pass it a string to print. It will export a `run` function that will invoke the imported `print` function.
Replace the code in `src/lib.rs` with the following Rust code:
```rust
extern "C" {
fn print(address: i32, length: i32);
}
#[no_mangle]
pub unsafe extern fn run() {
let message = "Hello world!";
print(message.as_ptr() as i32, message.len() as i32);
}
```
Note that this example passes the string as a pair of _address and length_. This is because WebAssembly only supports a few core types (such as integers and floats) and a "string" has no native representation in WebAssembly.
In the future, WebAssembly will support [interface types](https://hacks.mozilla.org/2019/08/webassembly-interface-types/) that will enable higher-level abstractions of types like strings so they can be represented in a natural way.
Also note that the _address_ is not actually a physical memory address within the address space of a process but an address within the _[WebAssembly memory](https://hacks.mozilla.org/2017/07/memory-in-webassembly-and-why-its-safer-than-you-think/)_ of the module. Thus the WebAssembly module has no direct access to the memory of the host environment.
## Building the WebAssembly module
Use `cargo build` to build the WebAssembly module:
```text
cargo build --target wasm32-unknown-unknown --release
```
This should create a `hello.wasm` file in the `target/wasm32-unknown-unknown/release` directory. We will use `hello.wasm` in the next section of the tutorial.
As this example is very simple and does not require any of the data from the custom sections of the WebAssembly module, you may use `wasm-strip` if you have the [WebAssembly Binary Toolkit](https://github.com/WebAssembly/wabt) installed:
```text
wasm-strip target/wasm32-unknown-unknown/release/hello.wasm
```
The resulting file should be less than 200 bytes.
# Using the WebAssembly module from .NET
## Installing a .NET Core 3.0 SDK
Install a [.NET Core 3.0 SDK](https://dotnet.microsoft.com/download/dotnet-core/3.0) for your platform if you haven't already.
This will add a `dotnet` command to your PATH.
## Creating the .NET Core project
The .NET program will be a simple console application, so create a new console project with `dotnet new`:
```text
mkdir tutorial
cd tutorial
dotnet new console
```
## Referencing the Wasmtime for .NET package
To use Wasmtime for .NET from the project, we need to add a reference to the [Wasmtime NuGet package](https://www.nuget.org/packages/Wasmtime):
```text
dotnet add package --version 0.0.1-alpha1 wasmtime
```
_Note that the `--version` option is required because the package is currently prerelease._
This will add a `PackageReference` to the project file so that Wasmtime for .NET can be used.
## Implementing the .NET code
Replace the contents of `Program.cs` with the following:
```c#
using System;
using Wasmtime;
namespace Tutorial
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("print", Module="env")]
public void Print(int address, int length)
{
var message = Instance.Externs.Memories[0].ReadString(address, length);
Console.WriteLine(message);
}
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("hello.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run();
}
}
}
```
The `Host` class is responsible for implementing the imported [functions](https://webassembly.github.io/spec/core/syntax/modules.html#functions), [globals](https://webassembly.github.io/spec/core/syntax/modules.html#globals), [memories](https://webassembly.github.io/spec/core/syntax/modules.html#memories), and [tables](https://webassembly.github.io/spec/core/syntax/modules.html#syntax-table) for the WebAssembly module. For Wasmtime for .NET, this is done via the [`Import`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.ImportAttribute.html) attribute applied to functions and fields of type [`Global<T>`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Global-1.html), [`MutableGlobal<T>`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.MutableGlobal-1.html), and [`Memory`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Memory.html) (support for WebAssembly tables is not yet implemented). The [`Instance`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.IHost.html#Wasmtime_IHost_Instance) property of the host is set during instantiation of the WebAssembly module.
Here the host is implementing an import of `print` in the `env` module, which is the default import module name for WebAssembly modules compiled using the Rust toolchain.
The [`Engine`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Engine.html) is used to create a [`Store`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Store.html) that will store all Wasmtime runtime objects, such as WebAssembly modules and their instantiations.
A WebAssembly module _instantiation_ is the stateful representation of a module that can be executed. Here, the code is casting the [`Instance`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Instance.html) to [`dynamic`](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic) which allows us to easily invoke the `run` function that was exported by the WebAssembly module.
Alternatively, the `run` function could be invoked without using the runtime binding of the `dynamic` feature like this:
```c#
...
using var instance = module.Instantiate(new Host());
instance.Externs.Functions[0].Invoke();
...
```
## Building the .NET application
Use `dotnet build` to build the .NET application:
```text
dotnet build
```
This will create a `tutorial.dll` in the `bin/Debug/netcoreapp3.0` directory that implements the .NET Core application. An executable `tutorial` (or `tutorial.exe` on Windows) should also be present in the same directory to run the application.
## Running the .NET application
Before running the application, we need to copy the `hello.wasm` file to the project directory.
Once the WebAssembly module is present in project directory, we can run the application:
```text
dotnet run
```
Alternatively, we can execute the program directly without building the application again:
```text
bin/Debug/netcoreapp3.0/tutorial
```
This should result in the following output:
```text
Hello world!
```
# Wrapping up
We did it! We executed a function written in Rust from .NET and a function implemented in .NET from Rust without much trouble at all. And, thanks to the design of WebAssembly, the Rust code was effectively sandboxed from accessing the memory of the .NET application.
Hopefully this introduction to Wasmtime for .NET has offered a small glipse of the potential of using WebAssembly from .NET.
# Introduction to Wasmtime for .NET
[Wasmtime](https://github.com/bytecodealliance/wasmtime) is a standalone runtime capable of executing [WebAssembly](https://webassembly.org/) outside of a web browser.
Wasmtime for .NET is a .NET API for Wasmtime. It enables .NET developers to easily instantiate and execute WebAssembly modules.
For this tutorial, we will create a WebAssembly module from a program written in Rust and use that WebAssembly module from a .NET Core 3.0 application.
# Creating a simple WebAssembly module
One of the reasons why WebAssembly is so exciting is that [many languages are able to target WebAssembly](https://github.com/appcypher/awesome-wasm-langs). This means, for example, a plugin model based on WebAssembly could enable developers to write sandboxed, cross-platform plugins in any number of languages.
Here I've decided to use [Rust](https://www.rust-lang.org/) for the implementation of the WebAssembly module. Rust is a modern systems programming language that can easily target WebAssembly.
If you wish to skip creating the WebAssembly module, download the [prebuilt WebAssembly module](https://raw.githubusercontent.com/bytecodealliance/wasmtime/master/crates/misc/dotnet/docs/wasm/intro/hello.wasm) from this tutorial, copy it to your .NET project directory, and continue from the _[Using the WebAssembly module from .NET](#using-the-webassembly-module-from-net)_ section.
## Installing a Rust toolchain
To get started with Rust, install [rustup](https://rustup.rs/), the manager for Rust toolchains.
This will install both a `rustup` command and a `cargo` command (for the active Rust toolchain) to your PATH.
## Installing the WebAssembly target
To target WebAssembly with the active Rust toolchain, install the WebAssembly [target triple](https://forge.rust-lang.org/release/platform-support.html):
```text
rustup target add wasm32-unknown-unknown
```
## Creating the Rust project
Create a new Rust library project named `hello`:
```text
cargo new --lib hello
cd hello
```
To target WebAssembly, the library needs to be built as a `cdylib` (dynamic library) rather than the default of a static Rust library. Add the following to the `Cargo.toml` file in the project root:
```toml
[lib]
crate-type = ["cdylib"]
```
## Implementing the WebAssembly code
The WebAssembly implementation will import a `print` function from the host environment and pass it a string to print. It will export a `run` function that will invoke the imported `print` function.
Replace the code in `src/lib.rs` with the following Rust code:
```rust
extern "C" {
fn print(address: i32, length: i32);
}
#[no_mangle]
pub unsafe extern fn run() {
let message = "Hello world!";
print(message.as_ptr() as i32, message.len() as i32);
}
```
Note that this example passes the string as a pair of _address and length_. This is because WebAssembly only supports a few core types (such as integers and floats) and a "string" has no native representation in WebAssembly.
In the future, WebAssembly will support [interface types](https://hacks.mozilla.org/2019/08/webassembly-interface-types/) that will enable higher-level abstractions of types like strings so they can be represented in a natural way.
Also note that the _address_ is not actually a physical memory address within the address space of a process but an address within the _[WebAssembly memory](https://hacks.mozilla.org/2017/07/memory-in-webassembly-and-why-its-safer-than-you-think/)_ of the module. Thus the WebAssembly module has no direct access to the memory of the host environment.
## Building the WebAssembly module
Use `cargo build` to build the WebAssembly module:
```text
cargo build --target wasm32-unknown-unknown --release
```
This should create a `hello.wasm` file in the `target/wasm32-unknown-unknown/release` directory. We will use `hello.wasm` in the next section of the tutorial.
As this example is very simple and does not require any of the data from the custom sections of the WebAssembly module, you may use `wasm-strip` if you have the [WebAssembly Binary Toolkit](https://github.com/WebAssembly/wabt) installed:
```text
wasm-strip target/wasm32-unknown-unknown/release/hello.wasm
```
The resulting file should be less than 200 bytes.
# Using the WebAssembly module from .NET
## Installing a .NET Core 3.0 SDK
Install a [.NET Core 3.0 SDK](https://dotnet.microsoft.com/download/dotnet-core/3.0) for your platform if you haven't already.
This will add a `dotnet` command to your PATH.
## Creating the .NET Core project
The .NET program will be a simple console application, so create a new console project with `dotnet new`:
```text
mkdir tutorial
cd tutorial
dotnet new console
```
## Referencing the Wasmtime for .NET package
To use Wasmtime for .NET from the project, we need to add a reference to the [Wasmtime NuGet package](https://www.nuget.org/packages/Wasmtime):
```text
dotnet add package --version 0.0.1-alpha1 wasmtime
```
_Note that the `--version` option is required because the package is currently prerelease._
This will add a `PackageReference` to the project file so that Wasmtime for .NET can be used.
## Implementing the .NET code
Replace the contents of `Program.cs` with the following:
```c#
using System;
using Wasmtime;
namespace Tutorial
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("print", Module="env")]
public void Print(int address, int length)
{
var message = Instance.Externs.Memories[0].ReadString(address, length);
Console.WriteLine(message);
}
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("hello.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run();
}
}
}
```
The `Host` class is responsible for implementing the imported [functions](https://webassembly.github.io/spec/core/syntax/modules.html#functions), [globals](https://webassembly.github.io/spec/core/syntax/modules.html#globals), [memories](https://webassembly.github.io/spec/core/syntax/modules.html#memories), and [tables](https://webassembly.github.io/spec/core/syntax/modules.html#syntax-table) for the WebAssembly module. For Wasmtime for .NET, this is done via the [`Import`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.ImportAttribute.html) attribute applied to functions and fields of type [`Global<T>`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Global-1.html), [`MutableGlobal<T>`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.MutableGlobal-1.html), and [`Memory`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Memory.html) (support for WebAssembly tables is not yet implemented). The [`Instance`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.IHost.html#Wasmtime_IHost_Instance) property of the host is set during instantiation of the WebAssembly module.
Here the host is implementing an import of `print` in the `env` module, which is the default import module name for WebAssembly modules compiled using the Rust toolchain.
The [`Engine`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Engine.html) is used to create a [`Store`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Store.html) that will store all Wasmtime runtime objects, such as WebAssembly modules and their instantiations.
A WebAssembly module _instantiation_ is the stateful representation of a module that can be executed. Here, the code is casting the [`Instance`](https://peterhuene.github.io/wasmtime.net/api/Wasmtime.Instance.html) to [`dynamic`](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic) which allows us to easily invoke the `run` function that was exported by the WebAssembly module.
Alternatively, the `run` function could be invoked without using the runtime binding of the `dynamic` feature like this:
```c#
...
using var instance = module.Instantiate(new Host());
instance.Externs.Functions[0].Invoke();
...
```
## Building the .NET application
Use `dotnet build` to build the .NET application:
```text
dotnet build
```
This will create a `tutorial.dll` in the `bin/Debug/netcoreapp3.0` directory that implements the .NET Core application. An executable `tutorial` (or `tutorial.exe` on Windows) should also be present in the same directory to run the application.
## Running the .NET application
Before running the application, we need to copy the `hello.wasm` file to the project directory.
Once the WebAssembly module is present in project directory, we can run the application:
```text
dotnet run
```
Alternatively, we can execute the program directly without building the application again:
```text
bin/Debug/netcoreapp3.0/tutorial
```
This should result in the following output:
```text
Hello world!
```
# Wrapping up
We did it! We executed a function written in Rust from .NET and a function implemented in .NET from Rust without much trouble at all. And, thanks to the design of WebAssembly, the Rust code was effectively sandboxed from accessing the memory of the .NET application.
Hopefully this introduction to Wasmtime for .NET has offered a small glipse of the potential of using WebAssembly from .NET.
One last note: _Wasmtime for .NET is currently in a very early stage of development and the API might change dramatically in the future_.

View File

@@ -1,2 +1,2 @@
- name: Introduction to Wasmtime for .NET
href: intro.md
- name: Introduction to Wasmtime for .NET
href: intro.md

View File

@@ -1,7 +1,7 @@
# Wasmtime for .NET
A .NET API for [Wasmtime](https://github.com/bytecodealliance/wasmtime).
Wasmtime is a standalone runtime for [WebAssembly](https://webassembly.org/), using the Cranelift JIT compiler.
Wasmtime for .NET enables .NET code to instantiate WebAssembly modules and to interact with them in-process.
# Wasmtime for .NET
A .NET API for [Wasmtime](https://github.com/bytecodealliance/wasmtime).
Wasmtime is a standalone runtime for [WebAssembly](https://webassembly.org/), using the Cranelift JIT compiler.
Wasmtime for .NET enables .NET code to instantiate WebAssembly modules and to interact with them in-process.

View File

@@ -1,21 +1,21 @@
{{!Copyright (c) Oscar Vasquez. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.}}
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{{#title}}{{title}}{{/title}}{{^title}}{{>partials/title}}{{/title}} {{#_appTitle}}| {{_appTitle}} {{/_appTitle}}</title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="{{#title}}{{title}}{{/title}}{{^title}}{{>partials/title}}{{/title}} {{#_appTitle}}| {{_appTitle}} {{/_appTitle}}">
<meta name="generator" content="docfx {{_docfxVersion}}">
{{#_description}}<meta name="description" content="{{_description}}">{{/_description}}
<link rel="shortcut icon" href="{{_rel}}{{{_appFaviconPath}}}{{^_appFaviconPath}}favicon.ico{{/_appFaviconPath}}">
<link rel="stylesheet" href="{{_rel}}styles/docfx.vendor.css">
<link rel="stylesheet" href="{{_rel}}styles/docfx.css">
<link rel="stylesheet" href="{{_rel}}styles/main.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<meta property="docfx:navrel" content="{{_navRel}}">
<meta property="docfx:tocrel" content="{{_tocRel}}">
{{#_noindex}}<meta name="searchOption" content="noindex">{{/_noindex}}
{{#_enableSearch}}<meta property="docfx:rel" content="{{_rel}}">{{/_enableSearch}}
{{#_enableNewTab}}<meta property="docfx:newtab" content="true">{{/_enableNewTab}}
{{!Copyright (c) Oscar Vasquez. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.}}
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{{#title}}{{title}}{{/title}}{{^title}}{{>partials/title}}{{/title}} {{#_appTitle}}| {{_appTitle}} {{/_appTitle}}</title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="{{#title}}{{title}}{{/title}}{{^title}}{{>partials/title}}{{/title}} {{#_appTitle}}| {{_appTitle}} {{/_appTitle}}">
<meta name="generator" content="docfx {{_docfxVersion}}">
{{#_description}}<meta name="description" content="{{_description}}">{{/_description}}
<link rel="shortcut icon" href="{{_rel}}{{{_appFaviconPath}}}{{^_appFaviconPath}}favicon.ico{{/_appFaviconPath}}">
<link rel="stylesheet" href="{{_rel}}styles/docfx.vendor.css">
<link rel="stylesheet" href="{{_rel}}styles/docfx.css">
<link rel="stylesheet" href="{{_rel}}styles/main.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<meta property="docfx:navrel" content="{{_navRel}}">
<meta property="docfx:tocrel" content="{{_tocRel}}">
{{#_noindex}}<meta name="searchOption" content="noindex">{{/_noindex}}
{{#_enableSearch}}<meta property="docfx:rel" content="{{_rel}}">{{/_enableSearch}}
{{#_enableNewTab}}<meta property="docfx:newtab" content="true">{{/_enableNewTab}}
</head>

View File

@@ -1,394 +1,394 @@
body {
color: #ccd5dc;
font-family: "Open Sans",sans-serif;
line-height: 1.5;
font-size: 14px;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
word-wrap: break-word;
background-color: #2d2d30;
}
h1 {
font-weight: 600;
font-size: 32px;
}
h2 {
font-weight: 600;
font-size: 24px;
line-height: 1.8;
}
h3 {
font-weight: 600;
font-size: 20px;
line-height: 1.8;
}
h5 {
font-size: 14px;
padding: 10px 0px;
}
article h1,
article h2,
article h3,
article h4 {
margin-top: 35px;
margin-bottom: 15px;
}
article h4 {
padding-bottom: 8px;
border-bottom: 2px solid #ddd;
}
.navbar-brand>img {
color: #2d2d30;
}
.navbar {
border: none;
}
.subnav {
border-top: 1px solid #ddd;
background-color: #333337;
}
.navbar-inverse {
background-color: #1e1e1e;
z-index: 100;
}
.navbar-inverse .navbar-nav>li>a,
.navbar-inverse .navbar-text {
color: #66666d;
background-color: #1e1e1e;
border-bottom: 3px solid transparent;
padding-bottom: 12px;
}
.navbar-inverse .navbar-nav>li>a:focus,
.navbar-inverse .navbar-nav>li>a:hover {
color: #c5c5de;
background-color: #1e1e1e;
border-bottom: 3px solid #333337;
transition: all ease 0.25s;
}
.navbar-inverse .navbar-nav>.active>a,
.navbar-inverse .navbar-nav>.active>a:focus,
.navbar-inverse .navbar-nav>.active>a:hover {
color: #c5c5de;
background-color: #1e1e1e;
border-bottom: 3px solid #333337;
transition: all ease 0.25s;
}
.navbar-form .form-control {
border: none;
border-radius: 0;
}
.toc .level1>li {
font-weight: 400;
}
.toc .nav>li>a {
color: #ccd5dc;
}
.sidefilter {
background-color: #2d2d30;
border-left: none;
border-right: none;
}
.sidefilter {
background-color: #2d2d30;
border-left: none;
border-right: none;
}
.toc-filter {
padding: 10px;
margin: 0;
background-color: #2d2d30;
}
.toc-filter>input {
border: none;
border-radius: unset;
background-color: #333337;
padding: 5px 0 5px 20px;
font-size: 90%
}
.toc-filter>input:focus {
color: #ccd5dc;
transition: all ease 0.25s;
}
.toc-filter>.filter-icon {
display: none;
}
.sidetoc>.toc {
background-color: #2d2d30;
overflow-x: hidden;
}
.sidetoc {
background-color: #2d2d30;
border: none;
}
.alert {
background-color: inherit;
border: none;
padding: 10px 0;
border-radius: 0;
}
.alert>p {
margin-bottom: 0;
padding: 5px 10px;
border-bottom: 1px solid;
background-color: #212123;
}
.alert>h5 {
padding: 10px 15px;
margin-top: 0;
margin-bottom: 0;
text-transform: uppercase;
font-weight: bold;
border-top: 2px solid;
background-color: #212123;
border-radius: none;
}
.alert>ul {
margin-bottom: 0;
padding: 5px 40px;
}
.alert-info{
color: #1976d2;
}
.alert-warning{
color: #f57f17;
}
.alert-danger{
color: #d32f2f;
}
pre {
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
word-break: break-all;
word-wrap: break-word;
background-color: #1e1e1e;;
border-radius: 0;
border: none;
}
code{
background: #1e1e1e !important;
border-radius: 2px;
}
.hljs{
color: #bbb;
}
.toc .nav > li.active > .expand-stub::before, .toc .nav > li.in > .expand-stub::before, .toc .nav > li.in.active > .expand-stub::before, .toc .nav > li.filtered > .expand-stub::before {
content: "▾";
}
.toc .nav > li > .expand-stub::before, .toc .nav > li.active > .expand-stub::before {
content: "▸";
}
.affix ul ul > li > a:before {
content: "|";
}
.breadcrumb .label.label-primary {
background: #444;
border-radius: 0;
font-weight: normal;
font-size: 100%;
}
#breadcrumb .breadcrumb>li a {
border-radius: 0;
font-weight: normal;
font-size: 85%;
display: inline;
padding: 0 .6em 0;
line-height: 1;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
color: #999;
}
#breadcrumb .breadcrumb>li a:hover{
color: #c5c5de;
transition: all ease 0.25s;
}
.breadcrumb > li + li:before {
content: "⯈";
font-size: 75%;
color: #1e1e1e;
padding: 0;
}
.toc .level1>li {
font-weight: 600;
font-size: 130%;
padding-left: 5px;
}
.footer {
border-top: none;
background-color: #1e1e1e;
padding: 15px 0;
font-size: 90%;
}
.toc .nav > li > a:hover, .toc .nav > li > a:focus {
color: #fff;
transition: all ease 0.1s;
}
.form-control {
background-color: #333337;
border: none;
border-radius: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
input#search-query:focus {
color: #c5c5de;
}
.table-bordered, .table-bordered>tbody>tr>td, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>td, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>thead>tr>th {
border: 1px solid #1E1E1E;
}
.table-striped>tbody>tr:nth-of-type(odd) {
background-color: #212123;
}
blockquote {
padding: 10px 20px;
margin: 0 0 10px;
font-size: 110%;
border-left: 5px solid #69696e;
color: #69696e;
}
.pagination>.disabled>a, .pagination>.disabled>a:focus, .pagination>.disabled>a:hover, .pagination>.disabled>span, .pagination>.disabled>span:focus, .pagination>.disabled>span:hover {
background-color: #333337;
border-color: #333337;
}
.breadcrumb>li, .pagination {
display: inline;
}
@media (min-width: 1600px){
.container {
width: 100%;
}
.sidefilter {
width: 20%;
}
.sidetoc{
width: 20%;
}
.article.grid-right {
margin-left: 21%;
}
}
code {
color:#8ec4f5;
}
.lang-text {
color:#ccd5dc;
}
button, a {
color: #8ec4f5;
}
.affix > ul > li.active > a, .affix > ul > li.active > a:before {
color: #8ec4f5;
}
.affix ul > li.active > a, .affix ul > li.active > a:before {
color: #8ec4f5;
}
.affix ul > li > a {
color: #d3cfcf;
}
button:hover, button:focus, a:hover, a:focus {
color: #339eff;
}
.toc .nav > li.active > a {
color: #8ec4f5;
}
.toc .nav > li.active > a:hover, .toc .nav > li.active > a:focus {
color: #339eff;
}
.navbar-inverse .navbar-nav > li > a, .navbar-inverse .navbar-text {
color: #9898a6;
}
.navbar-inverse .navbar-nav>.active>a,
.navbar-inverse .navbar-nav>.active>a:focus,
.navbar-inverse .navbar-nav>.active>a:hover {
color: #fff;
}
.hljs-attr,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-selector-pseudo,.hljs-title {
color:#b685ff;
}
.hljs-keyword,.hljs-selector-tag,.hljs-type {
color:#cc74a6;
}
.hljs-emphasis,.hljs-quote,.hljs-string,.hljs-strong,.hljs-template-variable,.hljs-variable {
color:#cc74a6
}
#breadcrumb .breadcrumb >li a {
color: #999;
}
.toc-filter > input {
color: #d3cfcf;
body {
color: #ccd5dc;
font-family: "Open Sans",sans-serif;
line-height: 1.5;
font-size: 14px;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
word-wrap: break-word;
background-color: #2d2d30;
}
h1 {
font-weight: 600;
font-size: 32px;
}
h2 {
font-weight: 600;
font-size: 24px;
line-height: 1.8;
}
h3 {
font-weight: 600;
font-size: 20px;
line-height: 1.8;
}
h5 {
font-size: 14px;
padding: 10px 0px;
}
article h1,
article h2,
article h3,
article h4 {
margin-top: 35px;
margin-bottom: 15px;
}
article h4 {
padding-bottom: 8px;
border-bottom: 2px solid #ddd;
}
.navbar-brand>img {
color: #2d2d30;
}
.navbar {
border: none;
}
.subnav {
border-top: 1px solid #ddd;
background-color: #333337;
}
.navbar-inverse {
background-color: #1e1e1e;
z-index: 100;
}
.navbar-inverse .navbar-nav>li>a,
.navbar-inverse .navbar-text {
color: #66666d;
background-color: #1e1e1e;
border-bottom: 3px solid transparent;
padding-bottom: 12px;
}
.navbar-inverse .navbar-nav>li>a:focus,
.navbar-inverse .navbar-nav>li>a:hover {
color: #c5c5de;
background-color: #1e1e1e;
border-bottom: 3px solid #333337;
transition: all ease 0.25s;
}
.navbar-inverse .navbar-nav>.active>a,
.navbar-inverse .navbar-nav>.active>a:focus,
.navbar-inverse .navbar-nav>.active>a:hover {
color: #c5c5de;
background-color: #1e1e1e;
border-bottom: 3px solid #333337;
transition: all ease 0.25s;
}
.navbar-form .form-control {
border: none;
border-radius: 0;
}
.toc .level1>li {
font-weight: 400;
}
.toc .nav>li>a {
color: #ccd5dc;
}
.sidefilter {
background-color: #2d2d30;
border-left: none;
border-right: none;
}
.sidefilter {
background-color: #2d2d30;
border-left: none;
border-right: none;
}
.toc-filter {
padding: 10px;
margin: 0;
background-color: #2d2d30;
}
.toc-filter>input {
border: none;
border-radius: unset;
background-color: #333337;
padding: 5px 0 5px 20px;
font-size: 90%
}
.toc-filter>input:focus {
color: #ccd5dc;
transition: all ease 0.25s;
}
.toc-filter>.filter-icon {
display: none;
}
.sidetoc>.toc {
background-color: #2d2d30;
overflow-x: hidden;
}
.sidetoc {
background-color: #2d2d30;
border: none;
}
.alert {
background-color: inherit;
border: none;
padding: 10px 0;
border-radius: 0;
}
.alert>p {
margin-bottom: 0;
padding: 5px 10px;
border-bottom: 1px solid;
background-color: #212123;
}
.alert>h5 {
padding: 10px 15px;
margin-top: 0;
margin-bottom: 0;
text-transform: uppercase;
font-weight: bold;
border-top: 2px solid;
background-color: #212123;
border-radius: none;
}
.alert>ul {
margin-bottom: 0;
padding: 5px 40px;
}
.alert-info{
color: #1976d2;
}
.alert-warning{
color: #f57f17;
}
.alert-danger{
color: #d32f2f;
}
pre {
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
word-break: break-all;
word-wrap: break-word;
background-color: #1e1e1e;;
border-radius: 0;
border: none;
}
code{
background: #1e1e1e !important;
border-radius: 2px;
}
.hljs{
color: #bbb;
}
.toc .nav > li.active > .expand-stub::before, .toc .nav > li.in > .expand-stub::before, .toc .nav > li.in.active > .expand-stub::before, .toc .nav > li.filtered > .expand-stub::before {
content: "▾";
}
.toc .nav > li > .expand-stub::before, .toc .nav > li.active > .expand-stub::before {
content: "▸";
}
.affix ul ul > li > a:before {
content: "|";
}
.breadcrumb .label.label-primary {
background: #444;
border-radius: 0;
font-weight: normal;
font-size: 100%;
}
#breadcrumb .breadcrumb>li a {
border-radius: 0;
font-weight: normal;
font-size: 85%;
display: inline;
padding: 0 .6em 0;
line-height: 1;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
color: #999;
}
#breadcrumb .breadcrumb>li a:hover{
color: #c5c5de;
transition: all ease 0.25s;
}
.breadcrumb > li + li:before {
content: "⯈";
font-size: 75%;
color: #1e1e1e;
padding: 0;
}
.toc .level1>li {
font-weight: 600;
font-size: 130%;
padding-left: 5px;
}
.footer {
border-top: none;
background-color: #1e1e1e;
padding: 15px 0;
font-size: 90%;
}
.toc .nav > li > a:hover, .toc .nav > li > a:focus {
color: #fff;
transition: all ease 0.1s;
}
.form-control {
background-color: #333337;
border: none;
border-radius: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
input#search-query:focus {
color: #c5c5de;
}
.table-bordered, .table-bordered>tbody>tr>td, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>td, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>thead>tr>th {
border: 1px solid #1E1E1E;
}
.table-striped>tbody>tr:nth-of-type(odd) {
background-color: #212123;
}
blockquote {
padding: 10px 20px;
margin: 0 0 10px;
font-size: 110%;
border-left: 5px solid #69696e;
color: #69696e;
}
.pagination>.disabled>a, .pagination>.disabled>a:focus, .pagination>.disabled>a:hover, .pagination>.disabled>span, .pagination>.disabled>span:focus, .pagination>.disabled>span:hover {
background-color: #333337;
border-color: #333337;
}
.breadcrumb>li, .pagination {
display: inline;
}
@media (min-width: 1600px){
.container {
width: 100%;
}
.sidefilter {
width: 20%;
}
.sidetoc{
width: 20%;
}
.article.grid-right {
margin-left: 21%;
}
}
code {
color:#8ec4f5;
}
.lang-text {
color:#ccd5dc;
}
button, a {
color: #8ec4f5;
}
.affix > ul > li.active > a, .affix > ul > li.active > a:before {
color: #8ec4f5;
}
.affix ul > li.active > a, .affix ul > li.active > a:before {
color: #8ec4f5;
}
.affix ul > li > a {
color: #d3cfcf;
}
button:hover, button:focus, a:hover, a:focus {
color: #339eff;
}
.toc .nav > li.active > a {
color: #8ec4f5;
}
.toc .nav > li.active > a:hover, .toc .nav > li.active > a:focus {
color: #339eff;
}
.navbar-inverse .navbar-nav > li > a, .navbar-inverse .navbar-text {
color: #9898a6;
}
.navbar-inverse .navbar-nav>.active>a,
.navbar-inverse .navbar-nav>.active>a:focus,
.navbar-inverse .navbar-nav>.active>a:hover {
color: #fff;
}
.hljs-attr,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-selector-pseudo,.hljs-title {
color:#b685ff;
}
.hljs-keyword,.hljs-selector-tag,.hljs-type {
color:#cc74a6;
}
.hljs-emphasis,.hljs-quote,.hljs-string,.hljs-strong,.hljs-template-variable,.hljs-variable {
color:#cc74a6
}
#breadcrumb .breadcrumb >li a {
color: #999;
}
.toc-filter > input {
color: #d3cfcf;
}

View File

@@ -1,7 +1,7 @@
- name: Articles
href: articles/
- name: API Documentation
href: api/
homepage: api/index.md
- name: GitHub Repo
href: https://github.com/bytecodealliance/wasmtime
- name: Articles
href: articles/
- name: API Documentation
href: api/
homepage: api/index.md
- name: GitHub Repo
href: https://github.com/bytecodealliance/wasmtime

View File

@@ -1,32 +1,32 @@
using System;
using Wasmtime;
namespace HelloExample
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("print_global")]
public void PrintGlobal()
{
Console.WriteLine($"The value of the global is: {Global.Value}.");
}
[Import("global")]
public readonly MutableGlobal<int> Global = new MutableGlobal<int>(1);
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("global.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run(20);
}
}
}
using System;
using Wasmtime;
namespace HelloExample
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("print_global")]
public void PrintGlobal()
{
Console.WriteLine($"The value of the global is: {Global.Value}.");
}
[Import("global")]
public readonly MutableGlobal<int> Global = new MutableGlobal<int>(1);
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("global.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run(20);
}
}
}

View File

@@ -1,21 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
</Project>

View File

@@ -1,29 +1,29 @@
using System;
using Wasmtime;
namespace HelloExample
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("hello")]
public void SayHello()
{
Console.WriteLine("Hello from C#, WebAssembly!");
}
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("hello.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run();
}
}
}
using System;
using Wasmtime;
namespace HelloExample
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("hello")]
public void SayHello()
{
Console.WriteLine("Hello from C#, WebAssembly!");
}
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("hello.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run();
}
}
}

View File

@@ -1,21 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
</Project>

View File

@@ -1,30 +1,30 @@
using System;
using Wasmtime;
namespace HelloExample
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("log")]
public void Log(int address, int length)
{
var message = Instance.Externs.Memories[0].ReadString(address, length);
Console.WriteLine($"Message from WebAssembly: {message}");
}
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("memory.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run();
}
}
}
using System;
using Wasmtime;
namespace HelloExample
{
class Host : IHost
{
public Instance Instance { get; set; }
[Import("log")]
public void Log(int address, int length)
{
var message = Instance.Externs.Memories[0].ReadString(address, length);
Console.WriteLine($"Message from WebAssembly: {message}");
}
}
class Program
{
static void Main(string[] args)
{
using var engine = new Engine();
using var store = engine.CreateStore();
using var module = store.CreateModule("memory.wasm");
using dynamic instance = module.Instantiate(new Host());
instance.run();
}
}
}

View File

@@ -1,21 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
</Project>

View File

@@ -1,85 +1,85 @@
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Wasmtime
{
/// <summary>
/// Represents the Wasmtime engine.
/// </summary>
public class Engine : IDisposable
{
/// <summary>
/// Constructs a new <see cref="Engine" />.
/// </summary>
public Engine()
{
Handle = Interop.wasm_engine_new();
if (Handle.IsInvalid)
{
throw new WasmtimeException("Failed to create Wasmtime engine.");
}
}
internal Engine(Interop.WasmConfigHandle config)
{
Handle = Interop.wasm_engine_new_with_config(config);
config.SetHandleAsInvalid();
if (Handle.IsInvalid)
{
throw new WasmtimeException("Failed to create Wasmtime engine.");
}
}
/// <summary>
/// Creates a new Wasmtime <see cref="Store" />.
/// </summary>
/// <returns>Returns the new <see cref="Store" />.</returns>
public Store CreateStore()
{
return new Store(this);
}
/// <summary>
/// Converts the WebAssembly text format to the binary format
/// </summary>
/// <returns>Returns the binary-encoded wasm module.</returns>
public byte[] WatToWasm(string wat)
{
var watBytes = Encoding.UTF8.GetBytes(wat);
unsafe
{
fixed (byte *ptr = watBytes)
{
Interop.wasm_byte_vec_t watByteVec;
watByteVec.size = (UIntPtr)watBytes.Length;
watByteVec.data = ptr;
if (!Interop.wasmtime_wat2wasm(Handle, ref watByteVec, out var bytes, out var error)) {
var errorSpan = new ReadOnlySpan<byte>(error.data, checked((int)error.size));
var message = Encoding.UTF8.GetString(errorSpan);
Interop.wasm_byte_vec_delete(ref error);
throw new WasmtimeException("failed to parse input wat: " + message);
}
var byteSpan = new ReadOnlySpan<byte>(bytes.data, checked((int)bytes.size));
var ret = byteSpan.ToArray();
Interop.wasm_byte_vec_delete(ref bytes);
return ret;
}
}
}
/// <inheritdoc/>
public void Dispose()
{
if (!Handle.IsInvalid)
{
Handle.Dispose();
Handle.SetHandleAsInvalid();
}
}
internal Interop.EngineHandle Handle { get; private set; }
}
}
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Wasmtime
{
/// <summary>
/// Represents the Wasmtime engine.
/// </summary>
public class Engine : IDisposable
{
/// <summary>
/// Constructs a new <see cref="Engine" />.
/// </summary>
public Engine()
{
Handle = Interop.wasm_engine_new();
if (Handle.IsInvalid)
{
throw new WasmtimeException("Failed to create Wasmtime engine.");
}
}
internal Engine(Interop.WasmConfigHandle config)
{
Handle = Interop.wasm_engine_new_with_config(config);
config.SetHandleAsInvalid();
if (Handle.IsInvalid)
{
throw new WasmtimeException("Failed to create Wasmtime engine.");
}
}
/// <summary>
/// Creates a new Wasmtime <see cref="Store" />.
/// </summary>
/// <returns>Returns the new <see cref="Store" />.</returns>
public Store CreateStore()
{
return new Store(this);
}
/// <summary>
/// Converts the WebAssembly text format to the binary format
/// </summary>
/// <returns>Returns the binary-encoded wasm module.</returns>
public byte[] WatToWasm(string wat)
{
var watBytes = Encoding.UTF8.GetBytes(wat);
unsafe
{
fixed (byte *ptr = watBytes)
{
Interop.wasm_byte_vec_t watByteVec;
watByteVec.size = (UIntPtr)watBytes.Length;
watByteVec.data = ptr;
if (!Interop.wasmtime_wat2wasm(Handle, ref watByteVec, out var bytes, out var error)) {
var errorSpan = new ReadOnlySpan<byte>(error.data, checked((int)error.size));
var message = Encoding.UTF8.GetString(errorSpan);
Interop.wasm_byte_vec_delete(ref error);
throw new WasmtimeException("failed to parse input wat: " + message);
}
var byteSpan = new ReadOnlySpan<byte>(bytes.data, checked((int)bytes.size));
var ret = byteSpan.ToArray();
Interop.wasm_byte_vec_delete(ref bytes);
return ret;
}
}
}
/// <inheritdoc/>
public void Dispose()
{
if (!Handle.IsInvalid)
{
Handle.Dispose();
Handle.SetHandleAsInvalid();
}
}
internal Interop.EngineHandle Handle { get; private set; }
}
}

View File

@@ -1,77 +1,77 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CSharp" Version="4.6.0" />
</ItemGroup>
<PropertyGroup>
<AssemblyName>Wasmtime.Dotnet</AssemblyName>
<PackageId>Wasmtime</PackageId>
<Version>$(WasmtimeVersion)-preview1</Version>
<Authors>Peter Huene</Authors>
<Owners>Peter Huene</Owners>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<RepositoryUrl>https://github.com/bytecodealliance/wasmtime</RepositoryUrl>
<PackageReleaseNotes>Initial release of Wasmtime for .NET.</PackageReleaseNotes>
<Summary>A .NET API for Wasmtime, a standalone WebAssembly runtime</Summary>
<PackageTags>webassembly, .net, wasm, wasmtime</PackageTags>
<Title>Wasmtime</Title>
<PackageDescription>
A .NET API for Wasmtime.
Wasmtime is a standalone runtime for WebAssembly, using the Cranelift JIT compiler.
Wasmtime for .NET enables .NET code to instantiate WebAssembly modules and to interact with them in-process.
</PackageDescription>
</PropertyGroup>
<Target Name="PackWasmtime" BeforeTargets="_GetPackageFiles">
<PropertyGroup>
<WasmtimeArchitecture>x86_64</WasmtimeArchitecture>
<ReleaseURLBase>https://github.com/bytecodealliance/wasmtime/releases/download/v$(WasmtimeVersion)/wasmtime-v$(WasmtimeVersion)-$(WasmtimeArchitecture)</ReleaseURLBase>
</PropertyGroup>
<ItemGroup>
<WasmtimeDownload Include="Linux">
<URL>$(ReleaseURLBase)-linux-c-api.tar.xz</URL>
<DownloadFolder>$(IntermediateOutputPath)wasmtime-linux</DownloadFolder>
<DownloadFilename>linux.tar.xz</DownloadFilename>
<WasmtimeLibraryFilename>libwasmtime.so</WasmtimeLibraryFilename>
<PackagePath>runtimes/linux-x64/native</PackagePath>
</WasmtimeDownload>
<WasmtimeDownload Include="macOS">
<URL>$(ReleaseURLBase)-macos-c-api.tar.xz</URL>
<DownloadFolder>$(IntermediateOutputPath)wasmtime-macos</DownloadFolder>
<DownloadFilename>macos.tar.xz</DownloadFilename>
<WasmtimeLibraryFilename>libwasmtime.dylib</WasmtimeLibraryFilename>
<PackagePath>runtimes/osx-x64/native</PackagePath>
</WasmtimeDownload>
<WasmtimeDownload Include="Windows">
<URL>$(ReleaseURLBase)-windows-c-api.zip</URL>
<DownloadFolder>$(IntermediateOutputPath)wasmtime-windows</DownloadFolder>
<DownloadFilename>windows.zip</DownloadFilename>
<WasmtimeLibraryFilename>wasmtime.dll</WasmtimeLibraryFilename>
<PackagePath>runtimes/win-x64/native</PackagePath>
</WasmtimeDownload>
</ItemGroup>
<Message Text="Downloading Wasmtime release." Importance="High" />
<DownloadFile SourceUrl="%(WasmtimeDownload.URL)" DestinationFolder="%(WasmtimeDownload.DownloadFolder)" DestinationFileName="%(WasmtimeDownload.DownloadFilename)" SkipUnchangedFiles="true" />
<Message Text="Decompressing Wasmtime release." Importance="High" />
<Exec Command="tar --strip-components 1 -xvzf %(WasmtimeDownload.DownloadFilename)" WorkingDirectory="%(WasmtimeDownload.DownloadFolder)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<Content Include="%(WasmtimeDownload.DownloadFolder)/lib/%(WasmtimeDownload.WasmtimeLibraryFilename)" Link="%(WasmtimeDownload.PackagePath)/%(WasmtimeDownload.WasmtimeLibraryFilename)">
<PackagePath>%(WasmtimeDownload.PackagePath)</PackagePath>
</Content>
</ItemGroup>
</Target>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CSharp" Version="4.6.0" />
</ItemGroup>
<PropertyGroup>
<AssemblyName>Wasmtime.Dotnet</AssemblyName>
<PackageId>Wasmtime</PackageId>
<Version>$(WasmtimeVersion)-preview1</Version>
<Authors>Peter Huene</Authors>
<Owners>Peter Huene</Owners>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<RepositoryUrl>https://github.com/bytecodealliance/wasmtime</RepositoryUrl>
<PackageReleaseNotes>Initial release of Wasmtime for .NET.</PackageReleaseNotes>
<Summary>A .NET API for Wasmtime, a standalone WebAssembly runtime</Summary>
<PackageTags>webassembly, .net, wasm, wasmtime</PackageTags>
<Title>Wasmtime</Title>
<PackageDescription>
A .NET API for Wasmtime.
Wasmtime is a standalone runtime for WebAssembly, using the Cranelift JIT compiler.
Wasmtime for .NET enables .NET code to instantiate WebAssembly modules and to interact with them in-process.
</PackageDescription>
</PropertyGroup>
<Target Name="PackWasmtime" BeforeTargets="_GetPackageFiles">
<PropertyGroup>
<WasmtimeArchitecture>x86_64</WasmtimeArchitecture>
<ReleaseURLBase>https://github.com/bytecodealliance/wasmtime/releases/download/v$(WasmtimeVersion)/wasmtime-v$(WasmtimeVersion)-$(WasmtimeArchitecture)</ReleaseURLBase>
</PropertyGroup>
<ItemGroup>
<WasmtimeDownload Include="Linux">
<URL>$(ReleaseURLBase)-linux-c-api.tar.xz</URL>
<DownloadFolder>$(IntermediateOutputPath)wasmtime-linux</DownloadFolder>
<DownloadFilename>linux.tar.xz</DownloadFilename>
<WasmtimeLibraryFilename>libwasmtime.so</WasmtimeLibraryFilename>
<PackagePath>runtimes/linux-x64/native</PackagePath>
</WasmtimeDownload>
<WasmtimeDownload Include="macOS">
<URL>$(ReleaseURLBase)-macos-c-api.tar.xz</URL>
<DownloadFolder>$(IntermediateOutputPath)wasmtime-macos</DownloadFolder>
<DownloadFilename>macos.tar.xz</DownloadFilename>
<WasmtimeLibraryFilename>libwasmtime.dylib</WasmtimeLibraryFilename>
<PackagePath>runtimes/osx-x64/native</PackagePath>
</WasmtimeDownload>
<WasmtimeDownload Include="Windows">
<URL>$(ReleaseURLBase)-windows-c-api.zip</URL>
<DownloadFolder>$(IntermediateOutputPath)wasmtime-windows</DownloadFolder>
<DownloadFilename>windows.zip</DownloadFilename>
<WasmtimeLibraryFilename>wasmtime.dll</WasmtimeLibraryFilename>
<PackagePath>runtimes/win-x64/native</PackagePath>
</WasmtimeDownload>
</ItemGroup>
<Message Text="Downloading Wasmtime release." Importance="High" />
<DownloadFile SourceUrl="%(WasmtimeDownload.URL)" DestinationFolder="%(WasmtimeDownload.DownloadFolder)" DestinationFileName="%(WasmtimeDownload.DownloadFilename)" SkipUnchangedFiles="true" />
<Message Text="Decompressing Wasmtime release." Importance="High" />
<Exec Command="tar --strip-components 1 -xvzf %(WasmtimeDownload.DownloadFilename)" WorkingDirectory="%(WasmtimeDownload.DownloadFolder)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<Content Include="%(WasmtimeDownload.DownloadFolder)/lib/%(WasmtimeDownload.WasmtimeLibraryFilename)" Link="%(WasmtimeDownload.PackagePath)/%(WasmtimeDownload.WasmtimeLibraryFilename)">
<PackagePath>%(WasmtimeDownload.PackagePath)</PackagePath>
</Content>
</ItemGroup>
</Target>
</Project>

View File

@@ -1,150 +1,150 @@
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;
namespace Wasmtime.Tests
{
public class FunctionExportsFixture : ModuleFixture
{
protected override string ModuleFileName => "FunctionExports.wat";
}
public class FunctionExportsTests : IClassFixture<FunctionExportsFixture>
{
public FunctionExportsTests(FunctionExportsFixture fixture)
{
Fixture = fixture;
}
private FunctionExportsFixture Fixture { get; set; }
[Theory]
[MemberData(nameof(GetFunctionExports))]
public void ItHasTheExpectedFunctionExports(string exportName, ValueKind[] expectedParameters, ValueKind[] expectedResults)
{
var export = Fixture.Module.Exports.Functions.Where(f => f.Name == exportName).FirstOrDefault();
export.Should().NotBeNull();
export.Parameters.Should().Equal(expectedParameters);
export.Results.Should().Equal(expectedResults);
}
[Fact]
public void ItHasTheExpectedNumberOfExportedFunctions()
{
GetFunctionExports().Count().Should().Be(Fixture.Module.Exports.Functions.Count);
}
public static IEnumerable<object[]> GetFunctionExports()
{
yield return new object[] {
"no_params_no_results",
Array.Empty<ValueKind>(),
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_i32_param_no_results",
new ValueKind[] {
ValueKind.Int32
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_i64_param_no_results",
new ValueKind[] {
ValueKind.Int64
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_f32_param_no_results",
new ValueKind[] {
ValueKind.Float32
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_f64_param_no_results",
new ValueKind[] {
ValueKind.Float64
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_param_of_each_type",
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"no_params_one_i32_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Int32,
}
};
yield return new object[] {
"no_params_one_i64_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Int64,
}
};
yield return new object[] {
"no_params_one_f32_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Float32,
}
};
yield return new object[] {
"no_params_one_f64_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Float64,
}
};
yield return new object[] {
"one_result_of_each_type",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64,
}
};
yield return new object[] {
"one_param_and_result_of_each_type",
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64,
},
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64,
}
};
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Xunit;
namespace Wasmtime.Tests
{
public class FunctionExportsFixture : ModuleFixture
{
protected override string ModuleFileName => "FunctionExports.wat";
}
public class FunctionExportsTests : IClassFixture<FunctionExportsFixture>
{
public FunctionExportsTests(FunctionExportsFixture fixture)
{
Fixture = fixture;
}
private FunctionExportsFixture Fixture { get; set; }
[Theory]
[MemberData(nameof(GetFunctionExports))]
public void ItHasTheExpectedFunctionExports(string exportName, ValueKind[] expectedParameters, ValueKind[] expectedResults)
{
var export = Fixture.Module.Exports.Functions.Where(f => f.Name == exportName).FirstOrDefault();
export.Should().NotBeNull();
export.Parameters.Should().Equal(expectedParameters);
export.Results.Should().Equal(expectedResults);
}
[Fact]
public void ItHasTheExpectedNumberOfExportedFunctions()
{
GetFunctionExports().Count().Should().Be(Fixture.Module.Exports.Functions.Count);
}
public static IEnumerable<object[]> GetFunctionExports()
{
yield return new object[] {
"no_params_no_results",
Array.Empty<ValueKind>(),
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_i32_param_no_results",
new ValueKind[] {
ValueKind.Int32
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_i64_param_no_results",
new ValueKind[] {
ValueKind.Int64
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_f32_param_no_results",
new ValueKind[] {
ValueKind.Float32
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_f64_param_no_results",
new ValueKind[] {
ValueKind.Float64
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"one_param_of_each_type",
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64
},
Array.Empty<ValueKind>()
};
yield return new object[] {
"no_params_one_i32_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Int32,
}
};
yield return new object[] {
"no_params_one_i64_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Int64,
}
};
yield return new object[] {
"no_params_one_f32_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Float32,
}
};
yield return new object[] {
"no_params_one_f64_result",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Float64,
}
};
yield return new object[] {
"one_result_of_each_type",
Array.Empty<ValueKind>(),
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64,
}
};
yield return new object[] {
"one_param_and_result_of_each_type",
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64,
},
new ValueKind[] {
ValueKind.Int32,
ValueKind.Int64,
ValueKind.Float32,
ValueKind.Float64,
}
};
}
}
}

View File

@@ -1,4 +1,4 @@
using FluentAssertions;
using FluentAssertions;
using System;
using System.Linq;
using Xunit;

View File

@@ -1,33 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.9.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
<ItemGroup>
<None Update="Modules/*.wat" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.9.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\src\Wasmtime.csproj" />
</ItemGroup>
<!-- This is needed as we're not referencing Wasmtime as a package. -->
<Target Name="BuildWasmtime" BeforeTargets="AssignTargetPaths">
<Message Text="Building Wasmtime from source." Importance="High" />
<Exec Command="$(BuildWasmtimeCommand)" StandardOutputImportance="Low" StandardErrorImportance="Low" />
<ItemGroup>
<None Include="$(WasmtimeOutputPath)/$(WasmtimeLibraryFilename)" Link="$(WasmtimeLibraryFilename)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Target>
<ItemGroup>
<None Update="Modules/*.wat" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>