简体   繁体   English

将原生抽象用于Node.js时如何管理内存?

[英]How do I manage memory when using Native Abstractions for Node.js?

I'm using Native Abstractions for Node.js (NAN) to call C++ functions from a node.js program. 我正在使用Node.js的本机抽象(NAN)从node.js程序调用C ++函数。

One C++ allocates a buffer using new char[] and returns it to my node.js program. 一个C ++使用新的char []分配一个缓冲区,并将其返回到我的node.js程序。

My question is that I do not know who is responsible for freeing this memory. 我的问题是我不知道谁负责释放此内存。 I'm using NanReturnValue in my C++ code to return a pointer to the buffer. 我在C ++代码中使用NanReturnValue返回指向缓冲区的指针。 If I delete[] it right after, the node.js code just gets garbage. 如果我立即删除[],则node.js代码只会变得垃圾。 But if I don't delete[] it at all, it appears there may be a memory leak (although its possible the leak is elsewhere). 但是,如果我根本不删除[],似乎可能存在内存泄漏(尽管泄漏的可能性在其他地方)。 The documentation is very sparse and it isn't clear who (whether javascript or C++) is responsible for deallocating this memory. 该文档非常稀疏,并且不清楚由谁(无论是JavaScript还是C ++)负责分配此内存。

You need to hook into the GC in v8 to get a callback to your C++ code letting you know that no JavaScript object has a reference to the buffer you returned. 您需要连接到v8中的GC才能获得对C ++代码的回调,从而使您知道没有JavaScript对象具有对您返回的缓冲区的引用。

In that C++ callback, you can delete the ArrayBuffer memory. 在该C ++回调中,您可以delete ArrayBuffer内存。

I'm sure you've seen these docs, but pay attention to the Nan::FreeCallBack() section: https://github.com/nodejs/nan/blob/master/doc/buffers.md#api_nan_free_callback 我确定您已经看过这些文档,但请注意Nan :: FreeCallBack()部分: https : //github.com/nodejs/nan/blob/master/doc/buffers.md#api_nan_free_callback

Here is a quick example: 这是一个简单的示例:

//defined before hand:
static void FreeCallback(char* data, void* message) {
   free(message);
}
    //some where in a function:
    Local<Object> buf_obj = NanNewBufferHandle((char*)zmq_msg_data(message), zmq_msg_size(message), FreeCallback, message);

For your buffer, there might be some differences, but I hope that gives you an idea of the direction to go. 对于您的缓冲区,可能会有一些差异,但是我希望可以使您对前进的方向有所了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM