review

The last article (WebAssembly- A Primer: Running C++ in a Web environment) gave you a rough introduction to what WebAssembly is, with a demo showing how to compile C/C++ code into.wASM files. This partial article will explain how to use it in the form of C code called from React.

Prepare the WASM function

Based on the example in the previous article, let’s rework hello.c and add an add function to support the addition of two numbers

#include <stdio.h>
#include <emscripten/emscripten.h>

int main(int argc, char ** argv) {
    printf("Hello World\n");
}

#ifdef __cplusplus
extern "C" {
#endif

int EMSCRIPTEN_KEEPALIVE add(int a, int b) {
  return a+b;
}

#ifdef __cplusplus
}
#endif
Copy the code

Then use the command to generate the corresponding JS and WASM files.

emcc hello.c -o ./hello.js -g1 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s ‘EXPORT_NAME=”hello”‘ -s “EXPORTED_RUNTIME_METHODS=[‘ccall’,’cwrap’]” -s ‘ENVIRONMENT=”web”

Explain the parameters a little bit

  • MODULARIZE MODULARIZE allows you to set module names to reduce import conflicts
  • EXPORT_ES6 is exported in ES6 syntax
  • EXPORT_NAME Specifies the module name
  • ENVIRONMENT specifies the operating ENVIRONMENT, which is web

This generates hello.js and hello.wasm

Create the React project

I’m going to use the basics here

create-react-app test-wasm-react

Then place hello.js in SCR and hello.wasm in public

Rewrite app.js to reference and use wASM

Transform the hello. Js

It will not work at this time, there will be a lot of errors, we need to modify the hello.js

  1. Increase the eslint – disable

    Add it to the top of hello.js

    /* eslint-disable */

  2. Change the path import.meta.url

    Var _scriptDir = import.meta.url; Var _scriptDir = ‘./hello.wasm’; , specify the public directory

  1. Modify the self. The location. The href

    Will scriptDirectory = self. Location. Href; Modified to scriptDirectory = window. The self. The location. The href; The script directory is then specified

  1. Remove binary load code

    Search wasmBinaryFile and comment out the getBinary and getBinaryPromise functions below it as shown:

These actions can be written as a sh script to complete, for some reference

sed -i.old '1s; ^; /* eslint-disable */; './hello.js

sed -i.old "s|import.meta.url|'./hello.wasm'|" ./hello.js

sed -i.old "s|self.location.href|window.self.location.href|" ./hello.js
Copy the code

Run the project

yarn start

As you can see, run has added 2 to 3, so one of the most basic C functions in React works

Subsequent updates

  1. Use Rust to implement
  2. Wasm grammar
  3. Complex function C implementation

If you like it, you can like it. If you have any questions, please comment