From f03f08596627d7388da5972f102bb36b82bed86f Mon Sep 17 00:00:00 2001 From: hellerve Date: Mon, 17 Feb 2020 11:22:31 +0100 Subject: [PATCH] initial --- README.md | 40 ++++++++++++++++++++++++++++++++++++++++ examples/set-bits.carp | 13 +++++++++++++ examples/simple.carp | 11 +++++++++++ main.carp | 9 +++++++++ 4 files changed, 73 insertions(+) create mode 100644 README.md create mode 100644 examples/set-bits.carp create mode 100644 examples/simple.carp create mode 100644 main.carp diff --git a/README.md b/README.md new file mode 100644 index 0000000..c6ce8b5 --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# inline-c + +is a simple module for defining C code inside Carp code. + +## Installation + +```clojure +(load "https://veitheller.de/git/carpentry/inline-c@0.0.1") +``` + +## Usage + +This module only provides one function, `inline-c` (it is a macro, actually +:shrug:). This function enables you to write C code inline as a string, to +express those things that are just kind of awkward in Carp (like complex +bit-twiddling) without having to include a helper every time. + +```clojure +(load "https://veitheller.de/git/carpentry/inline-c@0.0.1") + +(inline-c "int count_set_bits(int n) { + int count = 0; + while (n) { + count += n & 1; + n >>= 1; + } + return count; +}") +(register count-set-bits (Fn [Int] Int) "count_set_bits") + +(defn main [] (println* &(count-set-bits 462))) +``` + +The function is safe to be called multiple times, but it’s better to not call +it at all if it’s avoidable. Inlining your C in Carp does not magically make it +safe, naturally. + +
+ +Have fun! diff --git a/examples/set-bits.carp b/examples/set-bits.carp new file mode 100644 index 0000000..c4c4e7b --- /dev/null +++ b/examples/set-bits.carp @@ -0,0 +1,13 @@ +(load "main.carp") + +(inline-c "int count_set_bits(int n) { + int count = 0; + while (n) { + count += n & 1; + n >>= 1; + } + return count; +}") +(register count-set-bits (Fn [Int] Int) "count_set_bits") + +(defn main [] (println* &(count-set-bits 462))) diff --git a/examples/simple.carp b/examples/simple.carp new file mode 100644 index 0000000..4deed53 --- /dev/null +++ b/examples/simple.carp @@ -0,0 +1,11 @@ +(load "main.carp") + +(inline-c "long x() { return (1<<30)+12; }") +(register x (Fn [] Long)) +(inline-c "#include + +long y() { puts(\"inside c!\"); return 42; }") +(register y (Fn [] Long)) + + +(defn main [] (println* (+ (x) (y)))) diff --git a/main.carp b/main.carp new file mode 100644 index 0000000..c7dc59f --- /dev/null +++ b/main.carp @@ -0,0 +1,9 @@ +(defdynamic *c-counter* 0) + +(defndynamic inline-c [s] + (let [f (String.join [(Project.get-config "output-directory") + "carp_inline_c_generated" (str *c-counter*) ".h"])] + (do + (write-file f s) + (defdynamic *c-counter* (inc *c-counter*)) + (system-include f))))