Skip to content

Instantly share code, notes, and snippets.

@surma surma/_README.md Secret
Last active Aug 24, 2018

Embed
What would you like to do?

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>
@beaufortfrancois

This comment has been minimized.

Copy link

commented Aug 24, 2018

@surma Why async?

@surma

This comment has been minimized.

Copy link
Owner Author

commented Aug 24, 2018

@beaufortfrancois Habit. Removed it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.