aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlon Zakai <alonzakai@gmail.com>2012-02-23 10:16:01 -0800
committerAlon Zakai <alonzakai@gmail.com>2012-02-23 10:16:01 -0800
commit1710f5d258f7bc73477e5ccdc42a1e792504625a (patch)
treefa91c1aa9045f02df2476634e3ea7c1353a24754
parentd64b12dde5154bee81f38bab766dd9cac837b2c6 (diff)
cwrap (like ccall, but returns a wrapper function)
-rw-r--r--src/preamble.js14
-rwxr-xr-xtests/runner.py7
2 files changed, 20 insertions, 1 deletions
diff --git a/src/preamble.js b/src/preamble.js
index fce00fe2..6c29eade 100644
--- a/src/preamble.js
+++ b/src/preamble.js
@@ -414,6 +414,20 @@ function ccall(ident, returnType, argTypes, args) {
}
Module["ccall"] = ccall;
+// Returns a native JS wrapper for a C function. This is similar to ccall, but
+// returns a function you can call repeatedly in a normal way. For example:
+//
+// var my_function = cwrap('my_c_function', 'int', ['int', 'int']);
+// alert(my_function(5, 22));
+// alert(my_function(99, 12));
+//
+function cwrap(ident, returnType, argTypes) {
+ // TODO: optimize this, eval the whole function once instead of going through ccall each time
+ return function() {
+ return ccall(ident, returnType, argTypes, Array.prototype.slice.call(arguments));
+ }
+}
+
// Sets a value in memory in a dynamic way at run-time. Uses the
// type data. This is the same as makeSetValue, except that
// makeSetValue is done at compile-time and generates the needed
diff --git a/tests/runner.py b/tests/runner.py
index 428c1e98..ca8648dd 100755
--- a/tests/runner.py
+++ b/tests/runner.py
@@ -5014,6 +5014,11 @@ def process(filename):
setValue(p, 650, 'i32');
ret = ccall('pointer', 'pointer', ['pointer'], [p]); print([typeof ret, getValue(ret, 'i32')]);
print('*');
+ // part 2: cwrap
+ var multi = cwrap('multi', 'number', ['number', 'number', 'number', 'string']);
+ print(multi(2, 1.4, 3, 'atr'));
+ print(multi(8, 5.4, 4, 'bret'));
+ print('*');
}
};
\'\'\' + open(filename, 'r').read()
@@ -5022,7 +5027,7 @@ def process(filename):
Settings.EXPORTED_FUNCTIONS = ['_get_int', '_get_float', '_get_string', '_print_int', '_print_float', '_print_string', '_multi', '_pointer', '_malloc']
- self.do_run(src, '*\nnumber,5\nnumber,3.14\nstring,hello world\n12\nundefined\n14.56\nundefined\ncheez\nundefined\nmore\nnumber,10\n650\nnumber,21\n*\n', post_build=post)
+ self.do_run(src, '*\nnumber,5\nnumber,3.14\nstring,hello world\n12\nundefined\n14.56\nundefined\ncheez\nundefined\nmore\nnumber,10\n650\nnumber,21\n*\natr\n10\nbret\n53\n*\n', post_build=post)
def test_scriptaclass(self):
header_filename = os.path.join(self.get_dir(), 'header.h')