migueldeicaza / WasmerSharp

.NET Bindings for the Wasmer Runtime
MIT License
319 stars 24 forks source link

Implementation of builtin abort env import method? #22

Open waldobronchart opened 2 years ago

waldobronchart commented 2 years ago

Hello, I haven't been able to figure out how to parse the message argument from c# for the built-in abort method.

I currently have this:

        var abortImport = new Import("env",
            nameof(abort),
            new ImportFunction((WasmAbortCallbackDelegate)abort)
        );

        // ...

        _wasmInstance = new Instance(wasm, memoryImport, globalMemory, abortImport, funcImport);

    // ...

    public void abort(InstanceContext context, int messageLen, int fileName, int line, int column)
    {
        IntPtr memoryBase = context.GetMemory(0).Data;
        byte[] messageBytes = new byte[messageLen];
        Marshal.Copy(memoryBase, messageBytes, 0, messageLen);
        string messageStr = System.Text.Encoding.UTF8.GetString(messageBytes);

        Log($"Wasm Abort: {messageStr}, {fileName}, {line}, {column}");
    }

and I have also tried this:

            var memoryBase = ctx.GetMemory (0).Data;
            unsafe {
                var str = Encoding.UTF8.GetString ((byte*)memoryBase + ptr, len);
                Console.WriteLine ("Received this utf string: [{0}]", str);
            }

But both don't work (aka print an invalid string). When I write the contents of the byte array to the console log, it's just all 0's.

Caling Instance.LastError doesn't return anything either

Any guidance on how to implement this?

JamieSinn commented 2 years ago

assuming you're using assemblyscript to generate the WASM - you'll need to use their custom string format - https://www.assemblyscript.org/runtime.html#memory-layout - the length is 4 bytes before the address given.