虽然我没有完整的代码工作,但理论上如果你能够在 C++ 中这样做,那么只需使用node-gyp将 C++ 文件编译为 .node 文件,然后将其包含在你的 nodeJS 文件中.
所以一些示例伪代码,首先在一个新目录中创建一个 binding.gyp 文件,然后将一些代码放入其中,如下所示:
{
"targets": [
{
"target_name": "addon",
"sources": [
"hi.cc"
]
}
]
}
然后在同一个目录中(现在)创建另一个名为 的文件hi.cc
,并将您的 C++ 代码放入其中,再加上一些其他文件以从中制作节点模块。所以,根据上面提到的文档,你可以做这样的事情(未经测试):
/*don't know what includes you're using to git the Bitmap
and Graphics functions, but include them here */
/*then to make a node module*/
#include <node.h>
using namespace v8;
void GetImage(const FunctionCallbackInfi<Value>& args) {
Bitmap bm = new Bitmap(1024, 768);
Graphics g = Graphics.FromImage(bm);
IntPtr hdc = g.GetHdc();
Form1.PrintWindow(this.Handle, hdc, 0);
g.ReleaseHdc(hdc);
g.Flush();
/*
this is the key part, although I'm not
100% sure it will work since I don't
know exactly what type Graphics returns,
but basically just convert it somehow into
base64, or a plain old void* value
(as in this following example), then make a new
Local variable of it and set the return type
(or make a function callback). So first get the
Graphics variable into a void* of the data, then
convert it to an ArrayBuffer to use in NodeJS, based on this
answer. Anyway:
*/
Local<
ArrayBuffer
>
v =
ArrayBuffer::New(i, /*some void* value*/ temp, 5000/*or some length*/);
a.GetReturnValue().Set(v);
}
void Initialize(Local<Object> exports) {
NODE_SET_METHOD(exports, "hello", GetImage);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
然后确保您确实安装了 node-gyp 和正确的构建工具(请参阅上面的文档,但它非常多npm i -g node-gyp
),然后转到 build -> Release -> addon.node 并将其复制到您的主 nodeJS 目录,然后制作一个新的 nodeJS 文件或在现有文件中包含以下内容:
let addon = require("./addon"),
pictureData = Buffer.from(addon.hello()/* if you choose to return a base64 string instead, then insert: ,"base64"*/);