• It took me a while to get working, so thought I'd share what worked. Can be useful for off-loading some heavy duty calculations to c, to increase throughput.

    var c = E.compiledC(`
    // int fadd_byval(int,int)
    // void fadd_byref(int,int,int)
    typedef union {
        float f;
        int i;
    } floatint;
    int fadd_byval(int arg1,int arg2)
    {
    
      floatint farg1,farg2,farg3;
      farg1.i=arg1;farg2.i=arg2;
    
      farg3.f = farg1.f + farg2.f;
    
      return farg3.i;
    }
    void fadd_byref(floatint* arg1, floatint* arg2, floatint* arg3)
    {
      floatint farg1,farg2;
      farg1.i=arg1->i;
      farg2.i=arg2->i;
    
      floatint out;
      out.f = farg1.f + farg2.f;
    
      arg3->i = out.i;
    }
    
    `);
    
    {
    let cFloatArray = (val,len)=>{
      val = typeof val !== 'undefined' ? val : 0.0;
      len = typeof len !== 'undefined' ? len : 1;
    
      let fs = E.toFlatString((new Float32Array(len)).buffer);
      if ( !fs ) throw new Error("Required to be a flatstring");
      let f = new Float32Array(E.toArrayBuffer(fs));
    
      let i = new Int32Array(f.buffer);
      let r = E.getAddressOf(f.buffer,true);
      if ( r % 4 != 0 ) throw new Error("Required to be a aligned");
    
      f.fill(val);
      return {
        f: f,
        i: i,
        ref: r,
        store: s=>{
          i[0]=s;
        },
        get: ()=>f[0]
      };
    };
    
    //pass by val.
    let f1 = cFloatArray(0.9);
    let f2 = cFloatArray(1.2);
    let fSum = cFloatArray();
    fSum.store( c.fadd_byval(f1.i[0],f2.i[0]) );
    print(`pass by val answer : ${fSum.get()}`);
    
    
    //pass by reference.
    f1 = cFloatArray(0.65);
    f2 = cFloatArray(3.4);
    let fOut = cFloatArray();
    c.fadd_byref(f1.ref,f2.ref,fOut.ref);
    print(`pass by ref answer : ${fOut.get()}`);
    

    1) Use string literal `` in E.compiledC().
    2) Keep it declared in var = global scope.
    4) Flatstring + 4 byte Alignment (Thanks fanoush)

    Edit: Getting the ref version to work was extremely time-consuming because of some strange crash of reading the variables directly + performing floating math on them. Yet copying the inputs off of the stack seems to solve it. Also it is necessary to write to the pointers in int form ,not float.
    Edit: Fixed the crashes by forcing flat string. (cos alignment)

About

Avatar for d3nd3-o0 @d3nd3-o0 started