假设我有一个简单的 Hello, World! 用 C++ 或 C 编写的文件(任何能帮助我在 Node.js 中更轻松地使用它的东西,最好是 C),并希望从 Node.js 文件运行它。考虑到该文件将用于提高性能(将 CPU 密集型函数从 Node.js 更改为 C/C++),最有效的方法是什么?
我遇到了 the addons ,但在我看来,为了使用它,我必须转换大量代码才能将其转换为该格式。有没有更简单的方法?
最佳答案
我不明白为什么使用 child_process 会比其他选项慢。
我推荐:
// myCFile.c
#include <stdio.h>
int main(void){
// Processor-intensive computations
int x = 1+2+3;
// Send to node via standard output
printf("%d", x);
// Terminate the process
return 0;
}
编译:
gcc -o myExecutable myCFile.c
然后像这样使用child_process:
// File myNodeFile.js
const { exec } = require("child_process");
exec("./myExecutable", (error, stdout, stderr) => console.log(stdout));
关于c++ - 以高效的方式从 Node.js 运行 C 或 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100336/