Skip to content

Instantly share code, notes, and snippets.

@yeputons
Last active March 8, 2024 19:25
Show Gist options
  • Save yeputons/8591cc26cc1b61d3503b0cb3b4623001 to your computer and use it in GitHub Desktop.
Save yeputons/8591cc26cc1b61d3503b0cb3b4623001 to your computer and use it in GitHub Desktop.
Emscripten's embind's std::vector<std::string> example (tested with emscripten 2.0.6)
#!/bin/bash
em++ --bind cpp-code.cpp --post-js js-code.js -o output.js
node output.js
#include <emscripten/bind.h>
#include <iostream>
#include <string>
#include <vector>
void use_vector_string(const std::vector<std::string> &vec) {
std::cout << "size() = " << vec.size() << ", capacity()=" << vec.capacity() << "\n";
for (const auto &str : vec) {
std::cout << "vec[]=|" << str << "|\n";
}
}
EMSCRIPTEN_BINDINGS(EmbindVectorStringDemo) {
emscripten::register_vector<std::string>("StringList");
emscripten::function("use_vector_string", &use_vector_string);
}
Module.onRuntimeInitialized = function() { // Make sure EMSCRIPTEN_BINDINGS are called before we try to use them
const vec = new Module.StringList(); // Allocates std::vector<std::string> which is managed by JS
vec.push_back("hello"); // std::string and JavaScript strings are automatically interconverted
vec.push_back("world");
vec.push_back("1234");
Module.use_vector_string(vec);
vec.delete(); // Required to avoid C++ memory leaks and undestructed object
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment