Search code examples
javascriptmarshallingwebassembly.net-7.0

How to pass a C# string array to JavaScript using JSExport in WebAssembly?


Following is the boilerplate example from VS2022 WebAssembly console template. I'm trying to extend it to pass a C# array to read from the JS. I'm very new to WebAssembly, your help would be much appreciated.

C#

using System;
using System.Runtime.InteropServices.JavaScript;

public partial class MyClass
{
    //Working
    [JSExport]
    internal static string Greeting()
    {
        var text = $"Hello, World! Greetings from node version: {GetNodeVersion()}";
        return text;
    }
 
    //Working
    [JSImport("node.process.version", "main.mjs")]
    internal static partial string GetNodeVersion();


    // This is not working
    [JSExport]
    internal static string[] GetArray()
    {
        return new string[] { "1", "2" };
    }
}

JavaScript side

import { dotnet } from './dotnet.js'

const { setModuleImports, getAssemblyExports, getConfig } = await dotnet
    .withDiagnosticTracing(false)
    .create();

setModuleImports('main.mjs', {
    node: {
        process: {
            version: () => globalThis.process.version
        }
    }
});

const config = getConfig();
const exports = await getAssemblyExports(config.mainAssemblyName);
const text = exports.MyClass.Greeting();

//How to read the array? 
//This is not working
const strArray = exports.MyClass.GetArray();

console.log(text);

await dotnet.run();

Solution

  • Found the issue

    I was using the WebAssembly Console App project template in VS2022 .net7 and it was missing the static Main() method suitable for an entry point.

    Just add the following to the MyClass fix the issue.

    internal static void Main()
    {
    
    }