C++ で使うライブラリ
ライブラリは自分の C++ からも使えます。ヘッダーをインクルードして呼び出します。
crossbind.config.js は、zstd のパッケージ(crossbind のポート)を依存関係として挙げます。これで zstd.h がインクルードパスに入り、ライブラリがリンクされるので、native.h は普通の C++ プロジェクトと同じようにそれを使えます。
JavaScript から見えるのは、ヘッダーが定義する 2 つの関数だけです。API がテンプレートだけのライブラリや、少数の独自関数の裏に隠しておきたいライブラリには、この方法を使います。
試してみる
アルファベットのように繰り返しの少ないテキストを圧縮し、2 つのサイズを比べてみましょう。[■]native.h1#pragma once
#include <string>
#include <vector>
#include <zstd.h>
// zstd is a dependency of the project: include its header and
// call it. JavaScript calls the two functions defined here.
inline int compressedSize(const std::string &text) {
std::vector<char> out(ZSTD_compressBound(text.size()));
return ZSTD_compress(out.data(), out.size(), text.data(),
text.size(), 3);
}
inline std::string zstdVersion() {
return ZSTD_versionString();
}
[■]main.js2import {
initNative, compressedSize, zstdVersion,
} from './native/native.h';
await initNative();
const text = 'crossbind '.repeat(100);
console.log('zstd', await zstdVersion());
const packed = await compressedSize(text);
console.log(text.length, 'bytes become', packed);