Search code examples
v8embedded-v8

How to bind a c function with out parameters in v8?


The C function :

void foo(int* p){
    *p = 10;
}

And js call :

var a = 0;
foo(a);
console.log(a);//expect a to be 10

Solution

  • There is no way to have out-parameters for primitive types in JavaScript, and V8's API tries pretty hard not to create behaviors that are inconsistent with JavaScript, because that would be weird™.

    An alternative solution is to embed the field in an object:

    var a = {value: 0}
    foo(a);
    console.log(a.value);  // This can be made to print 10.
    

    With that approach, you can use the normal way of binding functions via V8's API, and on the C++ side simply modify the respective property of the object that was passed in.