Search code examples
node.jsnode-ffi

How to copy raw memory to Buffer in nodejs?


I use node and node-ffi. I get a callback from native/C that passes a (void *,size_t) to indicate a memory region with interesting data. I'd like to take that and create Buffer with the same contents.

Basically:

function callback_on_write(ptr, size)
{
    var buffer = new Buffer(size);
    buffer.somehow_copy_from_memory(ptr, size);
}

How do I copy raw memory to Buffer?


Solution

  • Use ref.reinterpret(buffer, size, offset).

    Returns a new Buffer instance with the specified size, with the same memory address as buffer.

    var ref = require('ref');
    
    function callback_on_write(ptr, size)
    {
        var buffer = ref.reinterpret(ptr, size);
    }