Search code examples
npapi

NPVariant to string array


I would like to pass an array of strings to a NPAPI plugin. How do I convert NPVariant to an array of strings?


Solution

  • Looks like you're going the other diretction from what jldupont suggested. When you pass an array in as a parameters to either a property or a method:

    var arrayData = [1,2,3,4,5];
    plugin.someProperty = arrayData;
    // -or-
    plugin.callSomeMethod(arrayData);
    

    That parameter will get to your NPObject as a NPVariant of type NPVariantType_Object. You then query the length property:

    NPObject *inObject = val->value.objectValue;
    NPVariant npvLength;
    NPN_GetProperty(npp, inObject, NPN_GetStringIdentifier("length"), &npvLength);
    

    and then you just do a for loop to get all the values:

    for (uint32_t i = 0; i < npvLength.value.intValue; i++) {
        NPVariant curValue;
        NPN_GetProperty(npp, inObject, NPN_GetIntIdentifier(i), &curValue);
        // Do something with curValue
    }
    

    Similarly, if you need to return an array to javascript, another option (other than writing a method to emulate an object, as I suggested in the thread that jldupont linked to) is to use NPN_GetValue to get the NPObject for the DOM window, and then Invoke "Array" on it with no parameters. This will return an empty JS Array object (as an NPObject*). Then you just loop through the items you want to return and call "push" with the item as the first (and only) parameter.

    Hope this helps