Update readme example with manual serdes for style

This commit is contained in:
Joshua Suskalo 2022-01-19 10:57:01 -06:00
parent 7ec2cd1575
commit 5ae32161b3

View file

@ -593,27 +593,29 @@ As an example, when wrapping a function that returns an array of big-endian
floats, the following code might be used. floats, the following code might be used.
``` clojure ``` clojure
(let [function-handle (ffi/make-downcall "returns_float_array" [::mem/pointer] ::mem/int) (def ^:private returns-float-array* (ffi/make-downcall "returns_float_array" [::mem/pointer] ::mem/int))
release-floats (ffi/make-downcall "releases_float_array" [::mem/pointer] ::mem/void) (def ^:private release-floats* (ffi/make-downcall "releases_float_array" [::mem/pointer] ::mem/void))
pointer-size (mem/size-of ::mem/pointer)
float-size (mem/size-of ::mem/float)] (defn returns-float-array
(defn returns-float-array []
[] (with-open [scope (mem/stack-scope)]
(with-open [scope (mem/stack-scope)] (let [out-floats (mem/alloc mem/pointer-size scope)
(let [out-floats (mem/alloc pointer-size scope) num-floats (function-handle (mem/address-of out-floats))
num-floats (function-handle (mem/address-of out-floats)) floats-addr (mem/read-address out-floats)
floats-addr (mem/read-address out-floats) floats-slice (mem/slice-global floats-addr (unchecked-multiply-int mem/float-size num-floats))]
floats-slice (mem/slice-global floats-addr (unchecked-multiply-int float-size num-floats)) ;; Using a try/finally to perform an operation when the stack frame exits,
ret (loop [floats (transient []) ;; but not to try to catch anything.
index 0] (try
(if (>= index num-floats) (loop [floats (transient [])
(persistent! floats) index 0]
(recur (conj! floats (mem/read-float floats-slice (if (>= index num-floats)
(unchecked-multiply-int index float-size) (persistent! floats)
mem/big-endian)) (recur (conj! floats (mem/read-float floats-slice
(unchecked-inc-int index))))] (unchecked-multiply-int index mem/float-size)
(release-floats floats-addr) mem/big-endian))
ret)))) (unchecked-inc-int index))))
(finally
(release-floats floats-addr))))))
``` ```
The above code manually performs all memory operations rather than relying on The above code manually performs all memory operations rather than relying on