01-04-2025, 07:50 AM
(This post was last modified: 01-04-2025, 07:59 AM by QUBIT_MATRIX.)
Yo! I didn't even know that it was possible, so here's what I found out.
First you will need emscripten:
To avoid running each time source ./emsdk_env.sh just add it to your shell profile.
When you've done that, you can start coding.
Set up a new index.html file like this:
And a hello.cpp file:
Now to compile the code, you run:
After that start a http server using python:
Then open the website in browser: http://localhost
You can also check the developer console for output since printf(); logs to console.
Some more information - whenever you declare a function in your c++ code, you need to use EMSCRIPTEN_KEEPALIVE otherwise it would result in c++ name mangling.
First you will need emscripten:
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
git pull
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh
To avoid running each time source ./emsdk_env.sh just add it to your shell profile.
When you've done that, you can start coding.
Set up a new index.html file like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebAssembly Example</title>
</head>
<body>
<h1>Welcome to WebAssembly Example</h1>
<p>This is a basic HTML structure for a WebAssembly project.</p>
<p id="rand"></p>
<script src="hello.js"></script>
<script>
Module.onRuntimeInitialized = function() {
Module._sayHello();
var number = Module._getRandomNumber();
console.log("Random number: " + number);
document.getElementById("rand").innerHTML = "Random number: " + number;
};
</script>
</body>
</html>
And a hello.cpp file:
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <emscripten.h>
#include <emscripten/bind.h>
#include <random>
extern "C" {
void sayHello();
int getRandomNumber();
}
EMSCRIPTEN_KEEPALIVE
void sayHello() {
printf("Hello, WebAssembly!\n");
}
EMSCRIPTEN_KEEPALIVE
int getRandomNumber() {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(1, 100);
int random_number = dist(mt);
printf("Random number: %d\n", random_number);
return random_number;
}
Now to compile the code, you run:
em++ hello.cpp -o hello.js -s WASM=1
After that start a http server using python:
python -m http.server 80
Then open the website in browser: http://localhost
You can also check the developer console for output since printf(); logs to console.
Some more information - whenever you declare a function in your c++ code, you need to use EMSCRIPTEN_KEEPALIVE otherwise it would result in c++ name mangling.
Secrets Channel: https://t.me/+JXdkoifUV0Q0ODVi