Permalink
Browse files

Added factorial C library example

  • Loading branch information...
1 parent 8f54311 commit e855c8811e413e582cdbe73845e8a6ed2556e9f8 @rbranson rbranson committed Nov 18, 2010
Showing with 58 additions and 1 deletion.
  1. +3 −1 README.md
  2. +6 −0 example/factorial/README
  3. +11 −0 example/factorial/factorial.c
  4. +14 −0 example/factorial/factorial.js
  5. +24 −0 example/factorial/wscript
View
@@ -5,7 +5,9 @@ http://github.com/rbranson/node-ffi
# DESCRIPTION
-node-ffi is a Node.js addon for loading and calling dynamic libraries using pure JavaScript. It can be used to create bindings to native libraries without writing any C++ code.
+node-ffi is a Node.js addon for loading and calling dynamic libraries using pure JavaScript. It can be used to create bindings to native libraries without writing any C++ code.
+
+It also simplifies the augmentation of node.js with C code as it takes care of handling the translation of types across JavaScript and C, which can add reams of boilerplate code to your otherwise simple C. See the `examples/factorial` for an example of this use case.
WARNING: node-ffi assumes you know what you're doing. You can pretty easily create situations where you will segfault the interpreter and unless you've got C debugger skills, you probably won't know what's going on.
View
@@ -0,0 +1,6 @@
+If you've already got node installed, this can be used:
+
+ $ node-waf build
+ ...
+ $ node factorial.js 35
+ Your output: 6399018521010896896
@@ -0,0 +1,11 @@
+#include <stdint.h>
+
+uint64_t factorial(int max) {
+ int i = max;
+ uint64_t result = 1;
+
+ while (i >= 2)
+ result *= i--;
+
+ return result;
+}
@@ -0,0 +1,14 @@
+var FFI = require("../../lib/ffi");
+
+var libfactorial = new FFI.Library("libfactorial", {
+ "factorial": [ "long", [ "uint64" ] ]
+});
+
+if (process.argv.length < 3) {
+ console.log("Arguments: " + process.argv[0] + " " + process.argv[1] + " <max>");
+ process.exit();
+}
+
+var output = libfactorial.factorial(parseInt(process.argv[2]))
+
+console.log("Your output: " + output);
View
@@ -0,0 +1,24 @@
+import Options
+from os import unlink, symlink, popen
+from os.path import exists
+from logging import fatal
+
+srcdir = '.'
+blddir = 'build'
+
+def set_options(opt):
+ opt.tool_options('compiler_cc')
+
+def configure(conf):
+ conf.check_tool('compiler_cc')
+
+def build(bld):
+ obj = bld.new_task_gen('cc', 'shlib')
+ obj.target = 'factorial'
+ obj.source = 'factorial.c'
+
+def shutdown():
+ if exists("build/default/libfactorial.dylib") and not exists("libfactorial.dylib"):
+ symlink("build/default/libfactorial.dylib", "libfactorial.dylib")
+ if exists("build/default/libfactorial.so") and not exists("libfactorial.so"):
+ symlink("build/default/libfactorial.so", "libfactorial.so")

0 comments on commit e855c88

Please sign in to comment.