Last active
March 8, 2024 19:25
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
em++ --bind cpp-code.cpp --post-js js-code.js -o output.js | |
node output.js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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