在 C++ 中使用库
库也可以供你自己的 C++ 使用:包含它的头文件并调用即可。
crossbind.config.js 把 zstd 的包(一个 crossbind port)列为依赖。这样 zstd.h 就会进入 include 路径,库也会被链接,因此 native.h 可以像任何 C++ 项目那样使用它。
JavaScript 只能看到头文件中定义的两个函数。对于 API 全部由模板构成的库,以及你更愿意藏在自己几个函数后面的库,都可以通过这种方式使用。
试一试
压缩一段重复较少的文本(比如字母表),然后比较两个大小。[■]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);