Skip to content

Instantly share code, notes, and snippets.

@automata
Created June 8, 2013 05:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save automata/5734209 to your computer and use it in GitHub Desktop.
Save automata/5734209 to your computer and use it in GitHub Desktop.
#!/bin/bash
emcc sin.cpp -o sin.js \
-s EXPORTED_FUNCTIONS="['_Sin_constructor','_Sin_destructor','_Sin_setFrequency','_Sin_setAmplitude','_Sin_getFrequency','_Sin_computeBuffer']"
cat sin-proxy.js >> sin.js
// get references to the exposed proxy functions
var Sin_constructor = Module.cwrap('Sin_constructor', 'number', ['number', 'number']);
var Sin_destructor = Module.cwrap('Sin_destructor', null, ['number']);
var Sin_setFrequency = Module.cwrap('Sin_setFrequency', null, ['number', 'number']);
var Sin_setAmplitude = Module.cwrap('Sin_setAmplitude', null, ['number', 'number']);
var Sin_getFrequency = Module.cwrap('Sin_getFrequency', 'number', ['number']);
var Sin_computeBuffer = Module.cwrap('Sin_computeBuffer', ['number'], ['number']);
Sin = function (freq, amp) {
that = {};
that.ptr = Sin_constructor(freq, amp);
that.destroy = function () {
Sin_destructor(that.ptr);
};
that.setFrequency = function (x) {
Sin_setFrequency(that.ptr, x);
};
that.setAmplitude = function (x) {
Sin_setAmplitude(that.ptr, x);
};
that.getFrequency = function () {
return Sin_getFrequency(that.ptr);
};
that.computeBuffer = function () {
return Sin_computeBuffer(that.ptr);
};
return that;
};
#include <math.h>
#include <stdlib.h>
class Sin {
float amplitude;
float frequency;
public:
Sin (float frequencyV, float amplitudeV) {
frequency = frequencyV;
amplitude = amplitudeV;
}
~Sin() {
}
void setFrequency(float v) {
frequency = v;
}
void setAmplitude(float v) {
amplitude = v;
}
float getFrequency() {
return frequency;
}
void computeBuffer(float *buffer) {
for (int i=0; i<44100; i++) {
buffer[i] = i;
}
}
};
//compile using "C" linkage to avoid name obfuscation
extern "C" {
//constructor, returns a pointer to the HelloWorld object
void *Sin_constructor(float freq, float amp) {
Sin* obj = new Sin(freq, amp);
return obj;
}
void Sin_setFrequency(Sin *s, float freq) {
s->setFrequency(freq);
}
void Sin_setAmplitude(Sin *s, float amp) {
s->setAmplitude(amp);
}
float Sin_getFrequency(Sin *s) {
return s->getFrequency();
}
float *Sin_computeBuffer(Sin *s) {
float *buffer;
s->computeBuffer(buffer);
return buffer;
}
void Sin_destructor(Sin *s) {
delete s;
}
};
// how can I access the computed array in JS? this doesn't work actually:
s = Sin(440.0, 1.0);
foo = s.computeBuffer();
bar = getValue(foo, 'float *');
// bar isn't an array...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment