Created
January 9, 2017 00:12
-
-
Save zzarcon/88473dac20ab641bc7e4a138fcba9a9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cwrap = function cwrap(ident, returnType, argTypes) { | |
argTypes = argTypes || []; | |
var cfunc = getCFunc(ident); | |
// When the function takes numbers and returns a number, we can just return | |
// the original function | |
var numericArgs = argTypes.every(function(type){ return type === 'number'}); | |
var numericRet = (returnType !== 'string'); | |
if ( numericRet && numericArgs) { | |
return cfunc; | |
} | |
// Creation of the arguments list (["$1","$2",...,"$nargs"]) | |
var argNames = argTypes.map(function(x,i){return '$'+i}); | |
var funcstr = "(function(" + argNames.join(',') + ") {"; | |
var nargs = argTypes.length; | |
if (!numericArgs) { | |
// Generate the code needed to convert the arguments from javascript | |
// values to pointers | |
ensureJSsource(); | |
funcstr += 'var stack = ' + JSsource['stackSave'].body + ';'; | |
for (var i = 0; i < nargs; i++) { | |
var arg = argNames[i], type = argTypes[i]; | |
if (type === 'number') continue; | |
var convertCode = JSsource[type + 'ToC']; // [code, return] | |
funcstr += 'var ' + convertCode.arguments + ' = ' + arg + ';'; | |
funcstr += convertCode.body + ';'; | |
funcstr += arg + '=(' + convertCode.returnValue + ');'; | |
} | |
} | |
// When the code is compressed, the name of cfunc is not literally 'cfunc' anymore | |
var cfuncname = parseJSFunc(function(){return cfunc}).returnValue; | |
// Call the function | |
funcstr += 'var ret = ' + cfuncname + '(' + argNames.join(',') + ');'; | |
if (!numericRet) { // Return type can only by 'string' or 'number' | |
// Convert the result to a string | |
var strgfy = parseJSFunc(function(){return Pointer_stringify}).returnValue; | |
funcstr += 'ret = ' + strgfy + '(ret);'; | |
} | |
funcstr += "if (typeof EmterpreterAsync === 'object') { assert(!EmterpreterAsync.state, 'cannot start async op with normal JS calling cwrap') }"; | |
if (!numericArgs) { | |
// If we had a stack, restore it | |
ensureJSsource(); | |
funcstr += JSsource['stackRestore'].body.replace('()', '(stack)') + ';'; | |
} | |
funcstr += 'return ret})'; | |
return eval(funcstr); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment