Alexis Paques Alexis Paques - 2 months ago 15
C++ Question

Convert args to double in NodeJS addon

I would like to convert the argument 0 to a long, to use it into a dll function.

The function is defined as

long function(long)


long __stdcall VBVMR_GetVoicemeeterVersion(long * pVersion);


And the call is like

void Voicemeeter_run(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = Isolate::GetCurrent();

if (args.Length() < 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Run needs 1 argument")));
return;
}

if (!args[0]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Argument 1 must be a number")));
return;
}

long type = args[0]->NumberValue();
//long type = 2;
long value = iVMR.VBVMR_RunVoicemeeter(type);
Local<Number> num = Number::New(isolate, value);
args.GetReturnValue().Set(num);
}


The I got the following warning :

..\vm-wrapper.cc(101): warning C4244: 'argument' : conversion de 'double' en 'long', perte possible de données [D:\Workspace\node-voicemeter\build\vm-wrapper.vcxproj]


Is there any other Node method? If I convert is to string then convert it to long via C native function I would not loose data, right? (I do not really care for the "data loss", but I would like to get rid of the warning)

Answer

You simply need to cast from double to long. You can do

double d = args[0]->NumberValue();
long l = static_cast<long>(d);

As for losing data, you will lose data if you receive a high value on output, but you can never enter a number big enough in javascript (double) to hit the upper limit of long.