Esempio n. 1
0
        /// <summary>
        /// Instantiates a WebAssembly module for the given host.
        /// </summary>
        /// <param name="wasi">The WASI instance to use for WASI imports.</param>
        /// <param name="host">The host to use for the WebAssembly module's instance.</param>
        /// <returns>Returns a new <see cref="Instance" />.</returns>
        public Instance Instantiate(Wasi wasi, IHost host = null)
        {
            if (!(host?.Instance is null))
            {
                throw new InvalidOperationException("The host has already been associated with an instantiated module.");
            }

            var instance = new Instance(this, wasi, host);

            if (!(host is null))
            {
                host.Instance = instance;
                return(instance);
            }

            return(instance);
        }
Esempio n. 2
0
        internal Instance(Module module, Wasi wasi = null, IHost host = null)
        {
            Host   = host;
            Module = module;

            // Save the bindings to root the objects.
            // Otherwise the GC may collect the callback delegates from FunctionHandles for example.
            _bindings = Binding.GetImportBindings(module, wasi, host)
                        .Select(b => b.Bind(module.Store, host))
                        .ToArray();

            unsafe
            {
                Handle = Interop.wasm_instance_new(
                    Module.Store.Handle,
                    Module.Handle,
                    _bindings.Select(h => ToExtern(h)).ToArray(),
                    out var trap);

                if (trap != IntPtr.Zero)
                {
                    throw TrapException.FromOwnedTrap(trap);
                }
            }

            if (Handle.IsInvalid)
            {
                throw new WasmtimeException($"Failed to instantiate module '{module.Name}'.");
            }

            Interop.wasm_instance_exports(Handle, out _externs);

            Externs = new Wasmtime.Externs.Externs(Module.Exports, _externs);

            _functions = Externs.Functions.ToDictionary(f => f.Name);
            _globals   = Externs.Globals.ToDictionary(g => g.Name);
        }