vector と map
std::vector の引数には通常の配列を渡せます。C++ が返す vector や map は、独自のメソッドを持つオブジェクトとして届きます。
mean は std::vector<double> を受け取り、main.js は配列を渡します。split は std::vector<std::string> を返し、m.toArray がそれを配列に変換します。m は initNative() が解決するモジュールです。
countWords は std::map<std::string, int> を返し、get(key) と size() で読みます。Web Worker の中では、返された vector はすでに通常の配列です。toArray はどちらも受け取るので、同じ行がそこでも動きます。
試してみる
文をスペースで分割し、counts にない単語を調べてみましょう。[■]native.h1#pragma once
#include <map>
#include <string>
#include <vector>
// A std::vector parameter takes a plain array.
double mean(const std::vector<double> &values);
// A returned vector or map arrives as an object of its own;
// the module's toArray makes an array of a vector.
std::vector<std::string> split(std::string text, char separator);
std::map<std::string, int> countWords(const std::string &text);
[■]main.js2import {
initNative, mean, split, countWords,
} from './native/native.h';
const m = await initNative();
console.log('mean:', await mean([3, 4, 8]));
const colors = await split('red,green,blue', ',');
console.log(await m.toArray(colors));
const counts = await countWords('the cat and the hat');
console.log('the:', await counts.get('the'));
C++、Rust、パッケージ、インポートが変わるまでは、コンパイルなしで実行します。
[■]出力「実行」または Ctrl+Enter で main.js を実行します。