Skip to content

Commit e714888

Browse files
authored
[wasm] improve samples (#74371)
- new sample for DLLImport on wasm - license headers - refactor withModuleConfig to advanced sample - removed withConsoleForwarding from samples
1 parent ecd6bbc commit e714888

File tree

20 files changed

+218
-120
lines changed

20 files changed

+218
-120
lines changed

src/mono/sample/wasm/Directory.Build.props

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
<ItemGroup>
3535
<ProjectReference Include="$(LibrariesProjectRoot)System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
3636
<ProjectReference Include="$(LibrariesProjectRoot)System.Runtime.InteropServices.JavaScript\gen\JSImportGenerator\JSImportGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
37+
<ProjectReference Include="$(LibrariesProjectRoot)System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
3738
</ItemGroup>
3839

3940
<!-- Import late, so properties like $(ArtifactsBinDir) are set -->
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Runtime.CompilerServices;
6+
using System.Runtime.InteropServices.JavaScript;
7+
using System.Runtime.InteropServices;
8+
9+
namespace Sample
10+
{
11+
public partial class Test
12+
{
13+
public static int Main(string[] args)
14+
{
15+
Console.WriteLine ("Hello, World!");
16+
return 0;
17+
}
18+
19+
[LibraryImport("fibonacci")]
20+
public static partial int Fibonacci(int n);
21+
22+
[JSImport("Sample.Test.add", "main.js")]
23+
internal static partial int Add(int a, int b);
24+
25+
[JSExport]
26+
internal static int TestMeaning()
27+
{
28+
// call to C code via [DllImport]
29+
var half = Fibonacci(8);
30+
// call back to JS via [JSImport]
31+
return Add(half, half);
32+
}
33+
34+
[JSExport]
35+
internal static bool IsPrime(int number)
36+
{
37+
if (number <= 1) return false;
38+
if (number == 2) return true;
39+
if (number % 2 == 0) return false;
40+
41+
var boundary = (int)Math.Floor(Math.Sqrt(number));
42+
43+
for (int i = 3; i <= boundary; i += 2)
44+
if (number % i == 0)
45+
return false;
46+
47+
return true;
48+
}
49+
}
50+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<WasmCopyAppZipToHelixTestDir Condition="'$(ArchiveTests)' == 'true'">true</WasmCopyAppZipToHelixTestDir>
4+
<WasmMainJSPath>main.js</WasmMainJSPath>
5+
<DebugSymbols>true</DebugSymbols>
6+
<DebugType>embedded</DebugType>
7+
<WasmDebugLevel>1</WasmDebugLevel>
8+
<GenerateRunScriptForSample Condition="'$(ArchiveTests)' == 'true'">true</GenerateRunScriptForSample>
9+
<RunScriptCommand>$(ExecXHarnessCmd) wasm test-browser --app=. --browser=Chrome $(XHarnessBrowserPathArg) --html-file=index.html --output-directory=$(XHarnessOutput) -- $(MSBuildProjectName).dll</RunScriptCommand>
10+
</PropertyGroup>
11+
<ItemGroup>
12+
<WasmExtraFilesToDeploy Include="index.html" />
13+
<NativeFileReference Include="fibonacci.c" />
14+
</ItemGroup>
15+
<PropertyGroup>
16+
<_SampleProject>Wasm.Advanced.Sample.csproj</_SampleProject>
17+
</PropertyGroup>
18+
<Target Name="RunSample" DependsOnTargets="RunSampleWithBrowser" />
19+
</Project>
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
int Fibonacci(int n) {
2+
int fnow = 0, fnext = 1, tempf;
3+
while(--n>0){
4+
tempf = fnow + fnext;
5+
fnow = fnext;
6+
fnext = tempf;
7+
}
8+
return fnext;
9+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<!DOCTYPE html>
2+
<!-- Licensed to the .NET Foundation under one or more agreements. -->
3+
<!-- The .NET Foundation licenses this file to you under the MIT license. -->
4+
<html>
5+
6+
<head>
7+
<title>Wasm Browser Advanced Sample</title>
8+
<meta charset="UTF-8">
9+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
10+
<link rel="modulepreload" href="./main.js" />
11+
<link rel="modulepreload" href="./dotnet.js" />
12+
</head>
13+
14+
<body>
15+
<h3 id="header">Wasm Browser Advanced Sample</h3>
16+
Answer to the Ultimate Question of Life, the Universe, and Everything is : <span id="out"></span>
17+
<script type='module' src="./main.js"></script>
18+
</body>
19+
20+
</html>
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
import { dotnet, exit } from './dotnet.js'
5+
6+
function add(a, b) {
7+
return a + b;
8+
}
9+
10+
try {
11+
const { runtimeBuildInfo, setModuleImports, getAssemblyExports, runMain, getConfig } = await dotnet
12+
.withElementOnExit()
13+
// 'withModuleConfig' is internal lower level API
14+
// here we show how emscripten could be further configured
15+
// It is prefered to use specific 'with***' methods instead in all other cases.
16+
.withModuleConfig({
17+
configSrc: "./mono-config.json",
18+
onConfigLoaded: (config) => {
19+
// This is called during emscripten `dotnet.wasm` instantiation, after we fetched config.
20+
console.log('user code Module.onConfigLoaded');
21+
// config is loaded and could be tweaked before the rest of the runtime startup sequence
22+
config.environmentVariables["MONO_LOG_LEVEL"] = "debug"
23+
},
24+
preInit: () => { console.log('user code Module.preInit'); },
25+
preRun: () => { console.log('user code Module.preRun'); },
26+
onRuntimeInitialized: () => {
27+
console.log('user code Module.onRuntimeInitialized');
28+
// here we could use API passed into this callback
29+
// Module.FS.chdir("/");
30+
},
31+
onDotnetReady: () => {
32+
// This is called after all assets are loaded.
33+
console.log('user code Module.onDotnetReady');
34+
},
35+
postRun: () => { console.log('user code Module.postRun'); },
36+
})
37+
.create();
38+
39+
// at this point both emscripten and monoVM are fully initialized.
40+
console.log('user code after dotnet.create');
41+
setModuleImports("main.js", {
42+
Sample: {
43+
Test: {
44+
add
45+
}
46+
}
47+
});
48+
49+
const config = getConfig();
50+
const exports = await getAssemblyExports(config.mainAssemblyName);
51+
const meaning = exports.Sample.Test.TestMeaning();
52+
console.debug(`meaning: ${meaning}`);
53+
if (!exports.Sample.Test.IsPrime(meaning)) {
54+
document.getElementById("out").innerHTML = `${meaning} as computed on dotnet ver ${runtimeBuildInfo.productVersion}`;
55+
console.debug(`ret: ${meaning}`);
56+
}
57+
58+
let exit_code = await runMain(config.mainAssemblyName, []);
59+
exit(exit_code);
60+
}
61+
catch (err) {
62+
exit(2, err);
63+
}

src/mono/sample/wasm/browser-eventpipe/main.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
14
import { dotnet } from "./dotnet.js";
25

36
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

src/mono/sample/wasm/browser-eventpipe/mock.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
14
/// @ts-check
25

36
/**

src/mono/sample/wasm/browser-nextjs/components/deepThought.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
14
import { useState, useEffect } from 'react'
25
import { dotnet } from '@microsoft/dotnet-runtime'
36

src/mono/sample/wasm/browser-nextjs/pages/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
14
import Head from 'next/head'
25
import DeepThought from '../components/deepThought'
36

0 commit comments

Comments
 (0)