WASM: Why `extern "C"` in JS bindings?

Hi there, writing my first bindings to some JS APIs. So far going well!

A question though: Why do binding blocks start with extern "C" { ... }? Shouldn't it be extern "JS" or similar?


1 Like

I have no idea really, but it seems to me that if you interface to Javascript code you are actually interfacing to the Javascript interpreter. Which is written in C/C++. Hence the "C" bindings.

The lowest common denominator, as it were.

There is no JS abi. Javascript doesn't use a memory layout or calling convention observable to the user. Instead wasm-bindgen uses the same abi used for interfacing with C(*) and then adds some wrapper javascript codd to translate between JS objects and WASM bytes.

(*) This is actually not quite true. When wasm32 support was added to rustc the calling convention was accidentally made different from what the standard C abi for wasm specifies. It can't be fixed without breaking wasm-bindgen. The wasm32-unknown-emscripten and wasm32-wasi targets do use the right calling convention though.


there's a extern "wasm" that someone was working on iirc

1 Like

I think a lot of tooling / systems talking to WASM programs talk in the C ABI?

The other reason being that, even if only wasm-bindgen-generated code talks to these methods, extern "C" already exists and is the main way in Rust to get methods with a guaranteed stable ABI.

1 Like

Isn't WASM an interpreter style environment? If so, wouldn't the abi be decided at JIT interpretation?

Sorry if what I'm saying makes no sense.

WASM is Intermediate Style (IL) like Java classes. You need a runtime to use it. What it allows as a public function is well defined (very few types and a seemingly strange functions taking two names.)
WASM is low level and misses alot of capability; which bindgen(or others) adds to make JS&Rust operate together.

My guess to the OP is no one cared, they just wanted to make it work by exposing the functionality LLVM provides. It takes a lot more effort to come up with something new. I would expect one of the reasons (that others haven't mentioned) not to change is it is good enough as is.


Thanks folks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.