1

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();
Kaf
  • 33,101
  • 7
  • 58
  • 78
  • According to: https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/import-export-interop?view=aspnetcore-7.0 You must MarshalAs to a string array. The Array of column indicates if the .NET type can be marshalled as a JS Array. Example: C# int[] (Int32) mapped to JS Array of Numbers. Not sure if this applies to Exports but maybe? – dynamiclynk Feb 03 '23 at 13:54
  • @dynamiclynk this is Webassembly but a Blazor example would be helpful if you have one? – Kaf Feb 03 '23 at 14:22

1 Answers1

1

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()
{

}
Kaf
  • 33,101
  • 7
  • 58
  • 78