Skip to content

Lifetime of a Buffer in a C++ addon #3222

Closed
@sgerace

Description

@sgerace

I'm working on an asynchronous C++ addon that is going to be processing buffers piped in from a stream, and I'm wondering the best way to persist the buffer data from the main event-loop thread into my worker thread. I'm basing much of my design on the way the Node.js zlib module is structured in the sense that I'm exposing a process function of my class that looks something like:

void Processor::ProcessAsync(const FunctionCallbackInfo<Value> &args) {
    Isolate* isolate = args.GetIsolate();

    // Unwrap processor object
    Processor *obj = ObjectWrap::Unwrap<Processor>(args.Holder());

    // Reset callback
    Local<Function> callback = Local<Function>::Cast(args[1]);
    obj->callback_.Reset(isolate, callback);

    // Get current buffer data...if this is set on obj, will is persist?
    unsigned char *buf = (unsigned char *)node::Buffer::Data(args[0]);
    size_t length = node::Buffer::Length(args[0]);

    // Build up the work request
    uv_work_t *request = &(obj->request_);
    uv_queue_work(uv_default_loop(), request, Processor::Process, Processor::After);

    // Return value
    args.GetReturnValue().Set(Undefined(isolate));
}

My question is whether or not the unsigned char *buf will persist throughout the lifetime of my class, or as I suspect, I will need to create a local copy of the data. I'm wondering if there is a way to force v8 to persist the data until I release it, but I'm just getting into the deep-end (or maybe the shallow end...) of interacting with v8 and would appreciate any guidance on how stuff like this is typically accomplished.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bufferIssues and PRs related to the buffer subsystem.c++Issues and PRs that require attention from people who are familiar with C++.questionIssues that look for answers.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions