0

So the quesion, I want to pass a pointer to a buffer I created in JS to a C++ library. How to get the address of a buffer in memory?

  • This would be unsafe. Instead, you'd use a [worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker) and [transfer](https://developer.mozilla.org/en-US/docs/Glossary/Transferable_objects) the underlying buffer or use a [shared buffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer). – jsejcksn Aug 09 '22 at 11:07

1 Answers1

0

I'm not superfamiliar with ffi, but it looks like Buffer instances are passed around by reference automatically (I'm using ffi-napi because ffi didn't want to install on macOS):

// C code
#include <stdio.h>

void show_my_buffer(void* buffer) {
  printf("Buffer: %s\n", (const char*) buffer);
}

// JS code
const ffi = require('ffi-napi');

const libmylibrary = ffi.Library('libmylibrary', {
  'show_my_buffer': [ 'void', [ 'void *' ] ]
});

const buffer = Buffer.from('hello world');
libmylibrary.show_my_buffer(buffer);

(And yes, I'm treating a buffer as if it were a string, which it isn't)

robertklep
  • 198,204
  • 35
  • 394
  • 381