AssemblyScript / assemblyscript

A TypeScript-like language for WebAssembly.
https://www.assemblyscript.org
Apache License 2.0
16.6k stars 650 forks source link

Interfacing with external C #2846

Closed spino17 closed 1 week ago

spino17 commented 1 month ago

Question

I want to know if it is possible that external C can be called inside assemblyscript. Any way to define C function prototype which will be provided by the host code through a WASM runtime like WAMR. Also, it is possible in assemblyscript that some functions can be exported in compiled wasm module.

dcodeIO commented 1 month ago

This is typically accomplished by specifying imports and exports. For example, an external host function can be declared and then called from AssemblyScript code:

@external("myModule", "add")
declare function add(a: i32, b: i32): i32;

add(1,2);

Or a function can be made callable by the host by exporting it from the entry file:

export function add(a: i32, b: i32): i32 {
  return a +b;
}

See also: Concepts / Module imports and exports

spino17 commented 1 month ago

Thanks @dcodeIO for the reply. I read the documentation you attached, however I believe assemblyscript is only enabled for js host. I can be completely wrong here. When I am using external decorator for wrapping console.log as consoleLog, and when I am calling it in my wasm module, WAMR gives me linking error. So I think it also expects the runtime to dynamically link certain functions for example console.log. Is there also any restriction of what runtime we are using ?

spino17 commented 1 month ago

So @dcodeIO below I am also attaching the code I have in /assembly/index.ts

// The entry file of your WebAssembly module.

@external("env", "console.log")
declare function consoleLog(s: string): void

export function main(): void {
  consoleLog("Hello, world");
}

This successfully compiles to .wasm file. Then when I am trying iwasm release.wasm in the /build dir, I am getting below error:

[05:10:53:628 - 1ED737AC0]: failed to check signature '(i)' and resolve pointer params for import function (env abort)

[05:10:53:717 - 1ED737AC0]: warning: failed to link import function (env, console.log)
[05:10:53:721 - 1ED737AC0]: warning: failed to link import function (env, abort)

#00: 0x0000 - console.log
#01: 0x00c6 - main

Exception: failed to call unlinked import function (env, console.log)
github-actions[bot] commented 2 weeks ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in one week if no further activity occurs. Thank you for your contributions!