Saturday, October 5, 2019

Webassembly Example C and C++ to HTML

Compiling C and C++ directly into a running web app is a thrill.

C Example

Save the following code to hello.c.
#include <stdio.h>
int main(int arg, char ** argv) {
  printf("Hello, world\n");
}
Note: point to the sdk! Run once after opening a terminal session, modifying the path to match your implementation.
$ source ~/dev/bin/emsdk/emsdk_env.sh --build=Release
Then, compile and run:
$ emcc hello.c -o hello.html
$ python -m SimpleHTTPServer 9000
open browser to http://localhost:9000/hello.html

C++ Example

Save the following code to dbldata.cpp.
#include <iostream>
struct Double_Data {
  Double_Data(const size_t size) : data(new double[size]) {}
  ~Double_Data() { delete [] data; }
  double *data;
};

Double_Data get_data() {
  Double_Data data(3);
  data.data[0] = 1.1; data.data[1] = 2.2; data.data[2] = 3.3;
  return data;
}

double sum_data(const Double_Data &d) {
  return d.data[0] + d.data[1] + d.data[2];
}

int main() {
  std::cout << sum_data(get_data()) << std::endl;
}
Note: point to the sdk! Run once after opening a terminal session, modifying the path to match your implementation.
$ source ~/dev/bin/emsdk/emsdk_env.sh --build=Release
Then, compile and run:
$ em++ dbldata.cpp -s -o dbldata.html
$ python -m SimpleHTTPServer 9000
open browser to http://localhost:9000/dbldata.html

C++ and Templates Example

Save the following code to dbldata.cpp.
#include <iostream>
template<typename Value_Type>
struct Data {
  Data(const size_t size) : data(new Value_Type[size]) {}
  ~Data() { delete [] data; }
  Value_Type *data;
};

template<typename Value_Type>
Data<Value_Type> get_data(const Value_Type &v1, 
                          const Value_Type &v2, 
                          const Value_Type &v3) {
  Data<Value_Type> d(3);
  d.data[0] = v1; d.data[1] = v2; d.data[2] = v3;
  return d;
}

template<typename Value_Type>
Value_Type sum_data(const Data<Value_Type> &d) {
  return d.data[0] + d.data[1] + d.data[2];
}

int main() {
  std::cout << sum_data(get_data(1.1, 3.3, 5.5)) << std::endl;
  std::cout << sum_data(get_data(11, 22, 33)) << std::endl;
}
Compile and run as before.

Running Example From bash Terminal

Verify the code is valid C++ by compiling and executing from the command line:
$ g++ dbldata.cpp -o dbldata
$ ./dbldata
9.9
66
The code in the C++ example was taken from Jason Turner's CppCon presentation "The Best Parts of C++"