Search code examples
javascriptfirefox-addonjsctypes

memset for structure vs array in js-ctypes


This is regarding the question memset has no DLL so how ctype it in combination with Any ideas what fillchar is doing?

I learned that memset can be used with array and structure type. However there is no sizeof feature so we have to do .length for arry and .size() for structure no?

I'm just a bit confused at how memset can work on structure and array please.


Solution

  • Well, the ctypes memset I provided can be used with arrays. But structures can be cast to arrays.

    Normally you'd not use memset on a structure, except when you want want to initialize it to 0s. But then again, normally you don't need to initialize it to 0 if you create the structure instance yourself with ctypes, as ctypes will take care of that (so you'd only need to initialize it when it is allocated by external code for whatever reason).

    Normally you'd just set the members of the structure:

    var tbb = new struct_TBButton();
    
    tbb.iBitmap = 1;
    tbb.idCommand = 2;
    

    In the really unusal case you need to memset it, then cast it to a (byte) array, which you can then memset.

    // Cast to a byte array (uint8_t == byte)
    var a = ctypes.cast(b, ctypes.uint8_t.array(struct_TBButton.size));
    
    // memset to something.
    // memset function from other question.
    function memset(array, val, size) {
     for (var i = 0; i < size; ++i) {
       array[i] = val;
     }
    } 
    memset(a, 0x10, a.length);
    
    // verify by checking iBitmap, which is an int(32), so 4 bytes,
    // so should be 10101010.
    console.log(tbb.iBitmap, tbb.iBitmap.toString(16), b.iBitmap == 0x10101010);
    //  269488144 "10101010" true