Skip to content

Instantly share code, notes, and snippets.

@surma

surma/_README.md Secret

Last active January 4, 2023 05:05
Show Gist options
  • Save surma/d04cd0fd896610575126d30de36d7eb6 to your computer and use it in GitHub Desktop.
Save surma/d04cd0fd896610575126d30de36d7eb6 to your computer and use it in GitHub Desktop.

This gist is part of my article “Emscripten’s embind”.

Build it with

$ emcc -s EXTRA_EXPORTED_RUNTIME_METHODS='["cwrap"]' -O3 nobind.cpp

or

$ docker run --rm -v $(pwd):/src trzeci/emscripten emcc -s EXTRA_EXPORTED_RUNTIME_METHODS='["cwrap"]' -O3 nobind.cpp

License Apache-2.0

/**
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <emscripten.h>
#include <stdint.h>
#include <stdlib.h>
#include <string>
extern "C"
EMSCRIPTEN_KEEPALIVE
double add(double a, double b) {
return a + b;
}
extern "C"
EMSCRIPTEN_KEEPALIVE
const char* exclaim(char* message) {
std::string *input = new std::string(message);
return (*input + "!").c_str();
}
extern "C"
EMSCRIPTEN_KEEPALIVE
int mymalloc(int size) {
return (int)malloc(size);
}
extern "C"
EMSCRIPTEN_KEEPALIVE
void myfree(int p) {
free((void *)p);
}
<script src="/a.out.js"></script>
<script>
Module.onRuntimeInitialized = _ => {
const api = {
add: Module.cwrap('add', 'number', ['number', 'number']),
exclaim: Module.cwrap('exclaim', 'number', ['number']),
malloc: Module.cwrap('mymalloc', 'number', ['number']),
free: Module.cwrap('myfree', '', ['number'])
};
function add(a, b) {
return api.add(a, b);
}
function exclaim(str) {
const utf8 = new TextEncoder('utf-8').encode(str);
const p = api.malloc(utf8.byteLength);
Module.HEAP8.set(utf8, p);
const p2 = api.exclaim(p);
const resultView = new Uint8Array(Module.HEAP8.buffer, p2, utf8.byteLength + 1);
return new TextDecoder('utf-8').decode(resultView);
}
console.log(add(22, 20));
console.log(exclaim('Hello World'));
};
</script>
@surma
Copy link
Author

surma commented Aug 24, 2018

@beaufortfrancois Habit. Removed it.

@waghamolm
Copy link

@surma Thank you for sharing the example. Your blogs related to WebAssembly are useful and knowledgeable.

Related to this example, I have one doubt.
In file nobind.html, and in function exclaim(str), memory pointed by p and p2 should be freed after the usage. Otherwise, there will be memory leak. Is that correct ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment