Skip to content

Instantly share code, notes, and snippets.

@palaniraja
Created July 7, 2024 19:15
Show Gist options
  • Save palaniraja/7798cc1a1cfb057cf22b79eea0ff580c to your computer and use it in GitHub Desktop.
Save palaniraja/7798cc1a1cfb057cf22b79eea0ff580c to your computer and use it in GitHub Desktop.
wasm file sharing between js and c
mkdir build && cd $_
emcmake cmake ..
make
emrun ../index.html
cmake_minimum_required(VERSION 3.12)
project(uppercase)
set(CMAKE_CXX_STANDARD 14)
add_executable(uppercase uppercase.cpp)
set_target_properties(uppercase PROPERTIES LINK_FLAGS "-s WASM=1 -s EXPORTED_FUNCTIONS=['_uppercase_file'] -s EXPORTED_RUNTIME_METHODS=['ccall','cwrap','FS'] -s FORCE_FILESYSTEM=1")
<!DOCTYPE html>
<html>
<body>
<button id="createFileButton" disabled>Create File</button>
<button id="processFileButton" disabled>Process File</button>
<script src="build/uppercase.js"></script>
<script>
Module.onRuntimeInitialized = function() {
document.getElementById('createFileButton').disabled = false;
document.getElementById('processFileButton').disabled = false;
document.getElementById('createFileButton').onclick = function() {
FS.mkdir('/working');
let content = 'helloworld'
FS.writeFile('/working/file.txt', content);
console.log('File created with content: ' + content);
};
document.getElementById('processFileButton').onclick = function() {
var result = Module.ccall('uppercase_file', 'string', ['string'], ['/working/file.txt']);
console.log(result);
};
};
</script>
</body>
</html>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <emscripten.h>
extern "C" {
EMSCRIPTEN_KEEPALIVE
char* uppercase_file(char* filename) {
std::ifstream file(filename);
std::string str((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
std::string result = "filename: ";
result += filename;
result += "\n";
result += "filesize: " + std::to_string(str.size());
result += "\n";
result += "filecontent (uppercase): " + str;
char* cstr = new char[result.length() + 1];
std::strcpy(cstr, result.c_str());
return cstr;
}
}
@palaniraja
Copy link
Author

when it works you should see this in the console

File created with content: helloworld 
filename: /working/file.txt
filesize: 10
filecontent (uppercase): HELLOWORLD

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