【问题标题】:Trying to make my C addon uses the same C runtime with the C runtime that NodeJS uses but got stuck试图让我的 C 插件使用与 NodeJS 使用的 C 运行时相同的 C 运行时,但被卡住了
【发布时间】:2020-08-14 16:28:59
【问题描述】:

如果你们必须知道我实际上在做什么,那就是:https://github.com/Meigyoku-Thmn/CSBinary(来自 .NET Core 的 BinaryReader 和 BinaryWriter 的端口)。

问题是,我的库没有File Buffering(请再说一遍,这与 NodeJS 中的 Buffer 类无关),我想利用 I/O 系统使用 C 运行时,而不必编写 BufferedFile 类(想想 .NET 中的 BufferedStream 类)。

在 C 语言中,如果您打开/创建一个文件 (fopen) 并获得一个 FILE* 实例,那么它在后台进行文件缓冲 ,您甚至可以使用setvbuf 函数设置文件缓冲区大小(同样,与 Buffer 类无关)。

而且我认为如果我手头有一个文件描述符(由 fs 模块创建),我可以使用 fdopen 函数将其包装/关联到 FILE* 实例中,并获取内置 C 运行时的文件免费缓冲。

不幸的是,NodeJS 似乎是使用静态链接构建的。所以我的插件使用了与 NodeJS 使用的不同的 C 运行时。从 NodeJS 创建的文件描述符不能直接在我的插件中使用,并且 libuv 没有类似于 fdopen 的任何东西。

根据 NodeJS 文档中的this section,有一种情况是 node-gyp 将“下载完整的源代码压缩包”并让我“完全访问全套 Node.js 依赖项”。可能是这样,但除了指定 nodedir 标志(这需要我手动准备“本地 Node.js 源图像”)之外,文档非常模糊。

所以这是死胡同吗,有人有这方面的经验,请帮助我。

【问题讨论】:

  • 我删除了 C++ 标签。

标签: node.js c crt node.js-addon


【解决方案1】:

最终,我找到了一种方法:

int nodejs_fd = gotFromJs();
// on POSIX-system, fd is process-wide, so I don't have to do anything
int fd = nodejs_fd;
// but on Windows, fd is just simulated on top of OS-Handle
// so it's bound to a specific C runtime, and my addon use a separate C runtime.
// therefore, I cannot just pass it to fdopen (EBADF)
// but I can still get the OS-handle
#ifdef _WIN32
HANDLE fh = (HANDLE)uv_get_osfhandle(nodejs_fd);
// so I can just open my own fd that points to it, side-by-side with the fd of NodeJS
fd = _open_osfhandle((intptr_t)fh, _O_RDONLY);
#endif
// and problem solved
FILE* file = fdopen(fd, "rb");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多