diff --git a/README.md b/README.md index 23831ac..c50f506 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,10 @@ doesn't remove the ability to write systems which minimize the cost of marshaling data and optimize for performance, to make use of the low-level access the FF&M API gives us. +- [Getting Started](igjoshua.github.io/coffi/01-Getting-Started.html) +- [API Documentation](igjoshua.github.io/coffi/) +- [Recent Changes](CHANGELOG.md) + ## Installation This library is available on Clojars, or as a git dependency. Add one of the following entries to the `:deps` key of your `deps.edn`: @@ -37,7 +41,7 @@ the following JVM arguments to your application. ``` You can specify JVM arguments in a particular invocation of the Clojure CLI with -the -J flag like so: +the `-J` flag like so: ``` sh clj -J--enable-native-access=ALL-UNNAMED diff --git a/deps.edn b/deps.edn index 843775d..1aed6e4 100644 --- a/deps.edn +++ b/deps.edn @@ -29,6 +29,7 @@ :version "v1.0.486" :description "A Foreign Function Interface in Clojure for JDK 22+." :source-paths ["src/clj"] + :doc-paths ["docs/articles"] :output-path "docs" :source-uri "https://github.com/IGJoshua/coffi/blob/{git-commit}/{filepath}#L{line}" :metadata {:doc/format :markdown}}} diff --git a/docs/01-Getting-Started.html b/docs/01-Getting-Started.html new file mode 100644 index 0000000..fa78e5d --- /dev/null +++ b/docs/01-Getting-Started.html @@ -0,0 +1,147 @@ + +Getting Started

Getting Started

+

Installation

+

This library is available on Clojars. Add one of the following entries to the :deps key of your deps.edn:

+
org.suskalo/coffi {:mvn/version "x.y.z"}
+io.github.IGJoshua/coffi {:git/tag "x.y.z" :git/sha "abcdef0"}
+
+

See GitHub for the latest releases.

+

If you use this library as a git dependency, you will need to prepare the library.

+
$ clj -X:deps prep
+
+

Coffi requires usage of the package java.lang.foreign, and most of the operations are considered unsafe by the JDK, and are therefore unavailable to your code without passing some command line flags. In order to use coffi, add the following JVM arguments to your application.

+
--enable-native-access=ALL-UNNAMED
+
+

You can specify JVM arguments in a particular invocation of the Clojure CLI with the -J flag like so:

+
clj -J--enable-native-access=ALL-UNNAMED
+
+

You can also specify them in an alias in your deps.edn file under the :jvm-opts key (see the next example) and then invoking the CLI with that alias using -M, -A, or -X.

+
{:aliases {:dev {:jvm-opts ["--enable-native-access=ALL-UNNAMED"]}}}
+
+

Other build tools should provide similar functionality if you check their documentation.

+

When creating an executable jar file, you can avoid the need to pass this argument by adding the manifest attribute Enable-Native-Access: ALL-UNNAMED to your jar.

+

Basic Usage

+

There are two major components to coffi and interacting with native code: manipulating off-heap memory, and loading native code for use with Clojure.

+

In the simplest cases, the native functions you call will work exclusively with built-in types, for example the function strlen from libc.

+
(require '[coffi.mem :as mem :refer [defalias]])
+(require '[coffi.ffi :as ffi :refer [defcfn]])
+
+(defcfn strlen
+  "Given a string, measures its length in bytes."
+  strlen [::mem/c-string] ::mem/long)
+
+(strlen "hello")
+;; => 5
+
+

The first argument to defcfn is the name of the Clojure var that will hold the native function reference, followed by an optional docstring and attribute map, then the C function identifier, including the name of the native symbol, a vector of argument types, and the return type.

+

If you wish to use a native function as an anonymous function, it can be done with the cfn function.

+
((ffi/cfn "strlen" [::mem/c-string] ::mem/long) "hello")
+;; => 5
+
+

If you want to use functions from libraries other than libc, then you’ll need to load them. Two functions are provided for this, load-system-library, and load-library. load-system-library takes a string which represents the name of a library that should be loaded via system lookup.

+
(ffi/load-system-library "z")
+
+

This will load libz from the appropriate place on the user’s load path.

+

Alternatively, load-library takes a file path to a dynamically loaded library.

+
(ffi/load-library "lib/libz.so")
+
+

This will load libz from the lib subdirectory of the current working directory. As you can see this requires the entire filename, including platform-specific file extensions.

+

If a library is attempted to be loaded but doesn’t exist or otherwise can’t be loaded, an exception is thrown. This can be convenient as any namespace with a load-library call at the top level cannot be required without the library being able to be loaded.

+

Primitive Types

+

Coffi defines a basic set of primitive types: - byte - short - int - long - char - float - double - pointer

+

Each of these types maps to their C counterpart. Values of any of these primitive types except for pointer will be cast with their corresponding Clojure function when they are passed as arguments to native functions. Additionally, the c-string type is defined, although it is not primitive.

+

Composite Types

+

In addition, some composite types are also defined in coffi, including struct and union types (unions will be discussed with serialization and deserialization). For an example C struct and function:

+
typedef struct point {
+    float x;
+    float y;
+} Point;
+
+Point zero(void) {
+    Point res = {};
+
+    res.x = 0.0;
+    res.y = 0.0;
+
+    return res;
+}
+
+

The corresponding coffi definition is like so:

+
(defcfn zero-point
+  "zero" [] [::mem/struct [[:x ::mem/float] [:y ::mem/float]]])
+
+(zero-point)
+;; => {:x 0.0,
+;;     :y 0.0}
+
+

Writing out struct definitions like this every time would get tedious, so the macro defalias is used to define a struct alias.

+
(defalias ::point
+  [::mem/struct
+   [[:x ::mem/float]
+    [:y ::mem/float]]])
+
+(defcfn zero-point
+  "zero" [] ::point)
+
+

Struct definitions do not include any padding by default. Functions for transforming struct types to include padding conforming to various standards can be found in coffi.layout.

+
(require '[coffi.layout :as layout])
+
+(defalias ::needs-padding
+  (layout/with-c-layout
+   [::mem/struct
+    [[:a ::mem/char]
+     [:x ::mem/float]]]))
+
+(mem/size-of ::needs-padding)
+;; => 8
+
+(mem/align-of ::needs-padding)
+;; => 4
+
+

Values deserialized with types produced from layout functions may include an extra :coffi.layout/padding key with a nil value.

+

A limitation of the defcfn macro in its current form is that types provided to it must be provided in a literal form, not as an expression that evaluates to a type. This means that if you wish to use a layout function on a struct you must define an alias for it before the type can be used as a type in defcfn.

+

In cases where a pointer to some data is required to pass as an argument to a native function, but doesn’t need to be read back in, the pointer primitive type can take a type argument.

+
[::mem/pointer ::mem/int]
+
+

Arrays are also supported via a type argument. Keep in mind that they are the array itself, and not a pointer to the array like you might see in certain cases in C.

+
[::mem/array ::mem/int 3]
+
+

Callbacks

+

In addition to these composite types, there is also support for Clojure functions.

+
[::ffi/fn [::mem/c-string] ::mem/int]
+
+

Be aware though that if an exception is thrown out of a callback that is called from C, the JVM will crash. The resulting crash log should include the exception type and message in the registers section, but it’s important to be aware of all the same. Ideally you should test your callbacks before actually passing them to native code.

+

When writing a wrapper library for a C library, it may be a good choice to wrap all passed Clojure functions in an additional function which catches all throwables, potentially notifies the user in some manner (e.g. logging), and returns a default value. This is on the wrapper library’s developer to decide when and where this is appropriate, as in some cases no reasonable default return value can be determined and it is most sensible to simply crash the JVM. This is the reason that coffi defaults to this behavior, as in the author’s opinion it is better to fail hard and fast rather than to attempt to produce a default and cause unexpected behavior later.

+

Another important thing to keep in mind is the expected lifetime of the function that you pass to native code. For example it is perfectly fine to pass an anonymous function to a native function if the callback will never be called again once the native function returns. If however it saves the callback for later use the JVM may collect it prematurely, causing a crash when the callback is later called by native code.

+

Variadic Functions

+

Some native functions can take any number of arguments, and in these cases coffi provides vacfn-factory (for “varargs C function factory”).

+
(def printf-factory (ffi/vacfn-factory "printf" [::mem/c-string] ::mem/int))
+
+

This returns a function of the types of the rest of the arguments which itself returns a native function wrapper.

+
(def print-int (printf-factory ::mem/int))
+
+(print-int "Some integer: %d\n" 5)
+;; Some integer: 5
+
+

At the moment there is no equivalent to defcfn for varargs functions.

+

Some native functions that are variadic use the type va_list to make it easier for other languages to call them in their FFI. At the time of writing, coffi does not support va-list, however it is a planned feature.

+

Global Variables

+

Some libraries include global variables or constants accessible through symbols. To start with, constant values stored in symbols can be fetched with const, or the parallel macro defconst

+
(def some-const (ffi/const "some_const" ::mem/int))
+(ffi/defconst some-const "some_const" ::mem/int)
+
+

This value is fetched once when you call const and is turned into a Clojure value. If you need to refer to a global variable, then static-variable (or parallel defvar) can be used to create a reference to the native value.

+
(def some-var (ffi/static-variable "some_var" ::mem/int))
+(ffi/defvar some-var "some_var" ::mem/int)
+
+

This variable is an IDeref. Each time you dereference it, the value will be deserialized from the native memory and returned. Additional functions are provided for mutating the variable.

+
(ffi/freset! some-var 5)
+;; => 5
+@some-var
+;; => 5
+
+

Be aware however that there is no synchronization on these types. The value being read is not read atomically, so you may see an inconsistent state if the value is being mutated on another thread.

+

A parallel function fswap! is also provided, but it does not provide any atomic semantics either.

+

The memory that backs the static variable can be fetched with the function static-variable-segment, which can be used to pass a pointer to the static variable to native functions that require it.

+
\ No newline at end of file diff --git a/docs/articles/01-Getting-Started.md b/docs/articles/01-Getting-Started.md new file mode 100644 index 0000000..f190cc2 --- /dev/null +++ b/docs/articles/01-Getting-Started.md @@ -0,0 +1,309 @@ +# Getting Started + +## Installation +This library is available on Clojars. Add one of the following entries to the +`:deps` key of your `deps.edn`: + +```clojure +org.suskalo/coffi {:mvn/version "x.y.z"} +io.github.IGJoshua/coffi {:git/tag "x.y.z" :git/sha "abcdef0"} +``` + +See GitHub for the [latest releases](https://github.com/IGJoshua/coffi/releases). + +If you use this library as a git dependency, you will need to prepare the +library. + +```sh +$ clj -X:deps prep +``` + +Coffi requires usage of the package `java.lang.foreign`, and most of the +operations are considered unsafe by the JDK, and are therefore unavailable to +your code without passing some command line flags. In order to use coffi, add +the following JVM arguments to your application. + +```sh +--enable-native-access=ALL-UNNAMED +``` + +You can specify JVM arguments in a particular invocation of the Clojure CLI with +the -J flag like so: + +``` sh +clj -J--enable-native-access=ALL-UNNAMED +``` + +You can also specify them in an alias in your `deps.edn` file under the +`:jvm-opts` key (see the next example) and then invoking the CLI with that alias +using `-M`, `-A`, or `-X`. + +``` clojure +{:aliases {:dev {:jvm-opts ["--enable-native-access=ALL-UNNAMED"]}}} +``` + +Other build tools should provide similar functionality if you check their +documentation. + +When creating an executable jar file, you can avoid the need to pass this +argument by adding the manifest attribute `Enable-Native-Access: ALL-UNNAMED` to +your jar. + +## Basic Usage +There are two major components to coffi and interacting with native code: +manipulating off-heap memory, and loading native code for use with Clojure. + +In the simplest cases, the native functions you call will work exclusively with +built-in types, for example the function `strlen` from libc. + +```clojure +(require '[coffi.mem :as mem :refer [defalias]]) +(require '[coffi.ffi :as ffi :refer [defcfn]]) + +(defcfn strlen + "Given a string, measures its length in bytes." + strlen [::mem/c-string] ::mem/long) + +(strlen "hello") +;; => 5 +``` + +The first argument to `defcfn` is the name of the Clojure var that will hold the +native function reference, followed by an optional docstring and attribute map, +then the C function identifier, including the name of the native symbol, a +vector of argument types, and the return type. + +If you wish to use a native function as an anonymous function, it can be done +with the `cfn` function. + +```clojure +((ffi/cfn "strlen" [::mem/c-string] ::mem/long) "hello") +;; => 5 +``` + +If you want to use functions from libraries other than libc, then you'll need to +load them. Two functions are provided for this, `load-system-library`, and +`load-library`. `load-system-library` takes a string which represents the name +of a library that should be loaded via system lookup. + +```clojure +(ffi/load-system-library "z") +``` + +This will load libz from the appropriate place on the user's load path. + +Alternatively, `load-library` takes a file path to a dynamically loaded library. + +```clojure +(ffi/load-library "lib/libz.so") +``` + +This will load libz from the lib subdirectory of the current working directory. +As you can see this requires the entire filename, including platform-specific +file extensions. + +If a library is attempted to be loaded but doesn't exist or otherwise can't be +loaded, an exception is thrown. This can be convenient as any namespace with a +`load-library` call at the top level cannot be required without the library +being able to be loaded. + +### Primitive Types +Coffi defines a basic set of primitive types: +- byte +- short +- int +- long +- char +- float +- double +- pointer + +Each of these types maps to their C counterpart. Values of any of these +primitive types except for `pointer` will be cast with their corresponding +Clojure function when they are passed as arguments to native functions. +Additionally, the `c-string` type is defined, although it is not primitive. + +### Composite Types +In addition, some composite types are also defined in coffi, including struct +and union types (unions will be discussed with serialization and +deserialization). For an example C struct and function: + +```c +typedef struct point { + float x; + float y; +} Point; + +Point zero(void) { + Point res = {}; + + res.x = 0.0; + res.y = 0.0; + + return res; +} +``` + +The corresponding coffi definition is like so: + +```clojure +(defcfn zero-point + "zero" [] [::mem/struct [[:x ::mem/float] [:y ::mem/float]]]) + +(zero-point) +;; => {:x 0.0, +;; :y 0.0} +``` + +Writing out struct definitions like this every time would get tedious, so the +macro `defalias` is used to define a struct alias. + +```clojure +(defalias ::point + [::mem/struct + [[:x ::mem/float] + [:y ::mem/float]]]) + +(defcfn zero-point + "zero" [] ::point) +``` + +Struct definitions do not include any padding by default. Functions for +transforming struct types to include padding conforming to various standards can +be found in `coffi.layout`. + +``` clojure +(require '[coffi.layout :as layout]) + +(defalias ::needs-padding + (layout/with-c-layout + [::mem/struct + [[:a ::mem/char] + [:x ::mem/float]]])) + +(mem/size-of ::needs-padding) +;; => 8 + +(mem/align-of ::needs-padding) +;; => 4 +``` + +Values deserialized with types produced from layout functions may include an +extra `:coffi.layout/padding` key with a nil value. + +A limitation of the `defcfn` macro in its current form is that types provided to +it must be provided in a literal form, not as an expression that evaluates to a +type. This means that if you wish to use a layout function on a struct you must +define an alias for it before the type can be used as a type in `defcfn`. + +In cases where a pointer to some data is required to pass as an argument to a +native function, but doesn't need to be read back in, the `pointer` primitive +type can take a type argument. + +```clojure +[::mem/pointer ::mem/int] +``` + +Arrays are also supported via a type argument. Keep in mind that they are the +array itself, and not a pointer to the array like you might see in certain cases +in C. + +```clojure +[::mem/array ::mem/int 3] +``` + +### Callbacks +In addition to these composite types, there is also support for Clojure +functions. + +```clojure +[::ffi/fn [::mem/c-string] ::mem/int] +``` + +Be aware though that if an exception is thrown out of a callback that is called +from C, the JVM will crash. The resulting crash log should include the exception +type and message in the registers section, but it's important to be aware of all +the same. Ideally you should test your callbacks before actually passing them to +native code. + +When writing a wrapper library for a C library, it may be a good choice to wrap +all passed Clojure functions in an additional function which catches all +throwables, potentially notifies the user in some manner (e.g. logging), and +returns a default value. This is on the wrapper library's developer to decide +when and where this is appropriate, as in some cases no reasonable default +return value can be determined and it is most sensible to simply crash the JVM. +This is the reason that coffi defaults to this behavior, as in the author's +opinion it is better to fail hard and fast rather than to attempt to produce a +default and cause unexpected behavior later. + +Another important thing to keep in mind is the expected lifetime of the function +that you pass to native code. For example it is perfectly fine to pass an +anonymous function to a native function if the callback will never be called +again once the native function returns. If however it saves the callback for +later use the JVM may collect it prematurely, causing a crash when the callback +is later called by native code. + +### Variadic Functions +Some native functions can take any number of arguments, and in these cases coffi +provides `vacfn-factory` (for "varargs C function factory"). + +```clojure +(def printf-factory (ffi/vacfn-factory "printf" [::mem/c-string] ::mem/int)) +``` + +This returns a function of the types of the rest of the arguments which itself +returns a native function wrapper. + +```clojure +(def print-int (printf-factory ::mem/int)) + +(print-int "Some integer: %d\n" 5) +;; Some integer: 5 +``` + +At the moment there is no equivalent to `defcfn` for varargs functions. + +Some native functions that are variadic use the type `va_list` to make it easier +for other languages to call them in their FFI. At the time of writing, coffi +does not support va-list, however it is a planned feature. + +### Global Variables +Some libraries include global variables or constants accessible through symbols. +To start with, constant values stored in symbols can be fetched with `const`, or +the parallel macro `defconst` + +```clojure +(def some-const (ffi/const "some_const" ::mem/int)) +(ffi/defconst some-const "some_const" ::mem/int) +``` + +This value is fetched once when you call `const` and is turned into a Clojure +value. If you need to refer to a global variable, then `static-variable` (or +parallel `defvar`) can be used to create a reference to the native value. + +```clojure +(def some-var (ffi/static-variable "some_var" ::mem/int)) +(ffi/defvar some-var "some_var" ::mem/int) +``` + +This variable is an `IDeref`. Each time you dereference it, the value will be +deserialized from the native memory and returned. Additional functions are +provided for mutating the variable. + +```clojure +(ffi/freset! some-var 5) +;; => 5 +@some-var +;; => 5 +``` + +Be aware however that there is no synchronization on these types. The value +being read is not read atomically, so you may see an inconsistent state if the +value is being mutated on another thread. + +A parallel function `fswap!` is also provided, but it does not provide any +atomic semantics either. + +The memory that backs the static variable can be fetched with the function +`static-variable-segment`, which can be used to pass a pointer to the static +variable to native functions that require it. diff --git a/docs/coffi.ffi.html b/docs/coffi.ffi.html index c843e2a..7cc8c2c 100644 --- a/docs/coffi.ffi.html +++ b/docs/coffi.ffi.html @@ -1,41 +1,41 @@ -coffi.ffi documentation

coffi.ffi

Functions for creating handles to native functions and loading native libraries.

+coffi.ffi documentation

coffi.ffi

Functions for creating handles to native functions and loading native libraries.

cfn

(cfn symbol args ret)

Constructs a Clojure function to call the native function referenced by symbol.

The function returned will serialize any passed arguments into the args types, and deserialize the return to the ret type.

If your args and ret are constants, then it is more efficient to call make-downcall followed by make-serde-wrapper because the latter has an inline definition which will result in less overhead from serdes.

-

const

(const symbol-or-addr type)

Gets the value of a constant stored in symbol-or-addr.

-

defcfn

macro

(defcfn name docstring? attr-map? symbol arg-types ret-type)(defcfn name docstring? attr-map? symbol arg-types ret-type native-fn & fn-tail)

Defines a Clojure function which maps to a native function.

+

const

(const symbol-or-addr type)

Gets the value of a constant stored in symbol-or-addr.

+

defcfn

macro

(defcfn name docstring? attr-map? symbol arg-types ret-type)(defcfn name docstring? attr-map? symbol arg-types ret-type native-fn & fn-tail)

Defines a Clojure function which maps to a native function.

name is the symbol naming the resulting var. symbol is a symbol or string naming the library symbol to link against. arg-types is a vector of qualified keywords representing the argument types. ret-type is a single qualified keyword representing the return type. fn-tail is the body of the function (potentially with multiple arities) which wraps the native one. Inside the function, native-fn is bound to a function that will serialize its arguments, call the native function, and deserialize its return type. If any body is present, you must call this function in order to call the native code.

If no fn-tail is provided, then the resulting function will simply serialize the arguments according to arg-types, call the native function, and deserialize the return value.

The number of args in the fn-tail need not match the number of arg-types for the native function. It need only call the native wrapper function with the correct arguments.

See serialize, deserialize, make-downcall.

-

defconst

macro

(defconst symbol docstring? symbol-or-addr type)

Defines a var named by symbol to be the value of the given type from symbol-or-addr.

-

defvar

macro

(defvar symbol docstring? symbol-or-addr type)

Defines a var named by symbol to be a reference to the native memory from symbol-or-addr.

-

ensure-symbol

(ensure-symbol symbol-or-addr)

Returns the argument if it is a MemorySegment, otherwise calls find-symbol on it.

-

find-symbol

(find-symbol sym)

Gets the MemorySegment of a symbol from the loaded libraries.

-

freset!

(freset! static-var newval)

Sets the value of static-var to newval, running it through serialize.

-

fswap!

(fswap! static-var f & args)

Non-atomically runs the function f over the value stored in static-var.

+

defconst

macro

(defconst symbol docstring? symbol-or-addr type)

Defines a var named by symbol to be the value of the given type from symbol-or-addr.

+

defvar

macro

(defvar symbol docstring? symbol-or-addr type)

Defines a var named by symbol to be a reference to the native memory from symbol-or-addr.

+

ensure-symbol

(ensure-symbol symbol-or-addr)

Returns the argument if it is a MemorySegment, otherwise calls find-symbol on it.

+

find-symbol

(find-symbol sym)

Gets the MemorySegment of a symbol from the loaded libraries.

+

freset!

(freset! static-var newval)

Sets the value of static-var to newval, running it through serialize.

+

fswap!

(fswap! static-var f & args)

Non-atomically runs the function f over the value stored in static-var.

The value is deserialized before passing it to f, and serialized before putting the value into static-var.

-

load-library

(load-library path)

Loads the library at path.

-

load-system-library

(load-system-library libname)

Loads the library named libname from the system’s load path.

-

make-downcall

(make-downcall symbol-or-addr args ret)

Constructs a downcall function reference to symbol-or-addr with the given args and ret types.

+

load-library

(load-library path)

Loads the library at path.

+

load-system-library

(load-system-library libname)

Loads the library named libname from the system’s load path.

+

make-downcall

(make-downcall symbol-or-addr args ret)

Constructs a downcall function reference to symbol-or-addr with the given args and ret types.

The function returned takes only arguments whose types match exactly the java-layout for that type, and returns an argument with exactly the java-layout of the ret type. This function will perform no serialization or deserialization of arguments or the return type.

If the ret type is non-primitive, then the returned function will take a first argument of a SegmentAllocator.

-

make-serde-varargs-wrapper

(make-serde-varargs-wrapper varargs-factory required-args ret-type)

Constructs a wrapper function for the varargs-factory which produces functions that serialize the arguments and deserialize the return value.

-

make-serde-wrapper

(make-serde-wrapper downcall arg-types ret-type)

Constructs a wrapper function for the downcall which serializes the arguments and deserializes the return value.

-

make-varargs-factory

(make-varargs-factory symbol required-args ret)

Returns a function for constructing downcalls with additional types for arguments.

+

make-serde-varargs-wrapper

(make-serde-varargs-wrapper varargs-factory required-args ret-type)

Constructs a wrapper function for the varargs-factory which produces functions that serialize the arguments and deserialize the return value.

+

make-serde-wrapper

(make-serde-wrapper downcall arg-types ret-type)

Constructs a wrapper function for the downcall which serializes the arguments and deserializes the return value.

+

make-varargs-factory

(make-varargs-factory symbol required-args ret)

Returns a function for constructing downcalls with additional types for arguments.

The required-args are the types of the first arguments passed to the downcall handle, and the values passed to the returned function are only the varargs types.

The returned function is memoized, so that only one downcall function will be generated per combination of argument types.

See make-downcall.

-

reify-libspec

(reify-libspec libspec)

Loads all the symbols specified in the libspec.

+

reify-libspec

(reify-libspec libspec)

Loads all the symbols specified in the libspec.

The value of each key of the passed map is transformed as by reify-symbolspec.

-

reify-symbolspec

multimethod

Takes a spec for a symbol reference and returns a live value for that type.

-

static-variable

(static-variable symbol-or-addr type)

Constructs a reference to a mutable value stored in symbol-or-addr.

+

reify-symbolspec

multimethod

Takes a spec for a symbol reference and returns a live value for that type.

+

static-variable

(static-variable symbol-or-addr type)

Constructs a reference to a mutable value stored in symbol-or-addr.

The returned value can be dereferenced, and has metadata.

See freset!, fswap!.

-

static-variable-segment

(static-variable-segment static-var)

Gets the backing MemorySegment from static-var.

+

static-variable-segment

(static-variable-segment static-var)

Gets the backing MemorySegment from static-var.

This is primarily useful when you need to pass the static variable’s address to a native function which takes an Addressable.

-

vacfn-factory

(vacfn-factory symbol required-args ret)

Constructs a varargs factory to call the native function referenced by symbol.

+

vacfn-factory

(vacfn-factory symbol required-args ret)

Constructs a varargs factory to call the native function referenced by symbol.

The function returned takes any number of type arguments and returns a specialized Clojure function for calling the native function with those arguments.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/coffi.layout.html b/docs/coffi.layout.html index 11c4c01..bff4af1 100644 --- a/docs/coffi.layout.html +++ b/docs/coffi.layout.html @@ -1,6 +1,6 @@ -coffi.layout documentation

coffi.layout

Functions for adjusting the layout of structs.

+coffi.layout documentation

coffi.layout

Functions for adjusting the layout of structs.

with-c-layout

(with-c-layout struct-spec)

Forces a struct specification to C layout rules.

This will add padding fields between fields to match C alignment requirements.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/coffi.mem.html b/docs/coffi.mem.html index 7cb91c2..cc459be 100644 --- a/docs/coffi.mem.html +++ b/docs/coffi.mem.html @@ -1,121 +1,121 @@ -coffi.mem documentation

coffi.mem

Functions for managing native allocations, memory arenas, and (de)serialization.

+coffi.mem documentation

coffi.mem

Functions for managing native allocations, memory arenas, and (de)serialization.

For any new type to be implemented, three multimethods must be overriden, but which three depends on the native representation of the type.

If the native representation of the type is a primitive (whether or not other data beyond the primitive is associated with it, as e.g. a pointer), then primitive-type must be overriden to return which primitive type it is serialized as, then serialize* and deserialize* should be overriden.

If the native representation of the type is a composite type, like a union, struct, or array, then c-layout must be overriden to return the native layout of the type, and serialize-into and deserialize-from should be overriden to allow marshaling values of the type into and out of memory segments.

address-of

(address-of addressable)

Gets the address of a given segment as a number.

-

address?

(address? addr)

Checks if an object is a memory address.

+

address?

(address? addr)

Checks if an object is a memory address.

nil is considered an address.

-

align-of

(align-of type)

The alignment in bytes of the given type.

-

alloc

(alloc size)(alloc size arena)(alloc size alignment arena)

Allocates size bytes.

+

align-of

(align-of type)

The alignment in bytes of the given type.

+

alloc

(alloc size)(alloc size arena)(alloc size alignment arena)

Allocates size bytes.

If an arena is provided, the allocation will be reclaimed when it is closed.

-

alloc-instance

(alloc-instance type)(alloc-instance type arena)

Allocates a memory segment for the given type.

-

alloc-with

(alloc-with allocator size)(alloc-with allocator size alignment)

Allocates size bytes using the allocator.

-

arena-allocator

(arena-allocator arena)

Constructs a SegmentAllocator from the given Arena.

+

alloc-instance

(alloc-instance type)(alloc-instance type arena)

Allocates a memory segment for the given type.

+

alloc-with

(alloc-with allocator size)(alloc-with allocator size alignment)

Allocates size bytes using the allocator.

+

arena-allocator

(arena-allocator arena)

Constructs a SegmentAllocator from the given Arena.

This is primarily used when working with unwrapped downcall functions. When a downcall function returns a non-primitive type, it must be provided with an allocator.

-

as-segment

(as-segment address)(as-segment address size)(as-segment address size arena)(as-segment address size arena cleanup)

Dereferences an address into a memory segment associated with the arena (default global).

-

auto-arena

(auto-arena)

Constructs a new memory arena that is managed by the garbage collector.

+

as-segment

(as-segment address)(as-segment address size)(as-segment address size arena)(as-segment address size arena cleanup)

Dereferences an address into a memory segment associated with the arena (default global).

+

auto-arena

(auto-arena)

Constructs a new memory arena that is managed by the garbage collector.

The arena may be shared across threads, and all resources created with it will be cleaned up at the same time, when all references have been collected.

This type of arena cannot be closed, and therefore should not be created in a with-open clause.

-

big-endian

The big-endian ByteOrder.

+

big-endian

The big-endian ByteOrder.

See little-endian, native-endian.

-

byte-layout

The MemoryLayout for a byte in native-endian ByteOrder.

-

c-layout

multimethod

Gets the layout object for a given type.

+

byte-layout

The MemoryLayout for a byte in native-endian ByteOrder.

+

c-layout

multimethod

Gets the layout object for a given type.

If a type is primitive it will return the appropriate primitive layout (see c-prim-layout).

Otherwise, it should return a GroupLayout for the given type.

-

char-layout

The MemoryLayout for a c-sized char in native-endian ByteOrder.

-

clone-segment

(clone-segment segment)(clone-segment segment arena)

Clones the content of segment into a new segment of the same size.

-

confined-arena

(confined-arena)

Constructs a new arena for use only in this thread.

+

char-layout

The MemoryLayout for a c-sized char in native-endian ByteOrder.

+

clone-segment

(clone-segment segment)(clone-segment segment arena)

Clones the content of segment into a new segment of the same size.

+

confined-arena

(confined-arena)

Constructs a new arena for use only in this thread.

The memory allocated within this arena is cheap to allocate, like a native stack.

The memory allocated within this arena will be cleared once it is closed, so it is usually a good idea to create it in a with-open clause.

-

copy-segment

(copy-segment dest src)

Copies the content to dest from src.

+

copy-segment

(copy-segment dest src)

Copies the content to dest from src.

Returns dest.

-

defalias

macro

(defalias new-type aliased-type)

Defines a type alias from new-type to aliased-type.

+

defalias

macro

(defalias new-type aliased-type)

Defines a type alias from new-type to aliased-type.

This creates needed serialization and deserialization implementations for the aliased type.

-

deserialize

(deserialize obj type)

Deserializes an arbitrary type.

+

deserialize

(deserialize obj type)

Deserializes an arbitrary type.

For types which have a primitive representation, this deserializes the primitive representation. For types which do not, this deserializes out of a segment.

-

deserialize*

multimethod

Deserializes a primitive object into a Clojure data structure.

+

deserialize*

multimethod

Deserializes a primitive object into a Clojure data structure.

This is intended for use with types that are returned as a primitive but which need additional processing before they can be returned.

-

deserialize-from

multimethod

Deserializes the given segment into a Clojure data structure.

+

deserialize-from

multimethod

Deserializes the given segment into a Clojure data structure.

For types that serialize to primitives, a default implementation will deserialize the primitive before calling deserialize*.

-

double-alignment

The alignment in bytes of a c-sized double.

-

double-layout

The MemoryLayout for a c-sized double in native-endian ByteOrder.

-

double-size

The size in bytes of a c-sized double.

-

float-alignment

The alignment in bytes of a c-sized float.

-

float-layout

The MemoryLayout for a c-sized float in native-endian ByteOrder.

-

float-size

The size in bytes of a c-sized float.

-

global-arena

(global-arena)

Constructs the global arena, which will never reclaim its resources.

+

double-alignment

The alignment in bytes of a c-sized double.

+

double-layout

The MemoryLayout for a c-sized double in native-endian ByteOrder.

+

double-size

The size in bytes of a c-sized double.

+

float-alignment

The alignment in bytes of a c-sized float.

+

float-layout

The MemoryLayout for a c-sized float in native-endian ByteOrder.

+

float-size

The size in bytes of a c-sized float.

+

global-arena

(global-arena)

Constructs the global arena, which will never reclaim its resources.

This arena may be shared across threads, but is intended mainly in cases where memory is allocated with alloc but is either never freed or whose management is relinquished to a native library, such as when returned from a callback.

-

int-alignment

The alignment in bytes of a c-sized int.

-

int-layout

The MemoryLayout for a c-sized int in native-endian ByteOrder.

-

int-size

The size in bytes of a c-sized int.

-

java-layout

(java-layout type)

Gets the Java class to an argument of this type for a method handle.

+

int-alignment

The alignment in bytes of a c-sized int.

+

int-layout

The MemoryLayout for a c-sized int in native-endian ByteOrder.

+

int-size

The size in bytes of a c-sized int.

+

java-layout

(java-layout type)

Gets the Java class to an argument of this type for a method handle.

If a type serializes to a primitive it returns return a Java primitive type. Otherwise, it returns MemorySegment.

-

java-prim-layout

Map of primitive type names to the Java types for a method handle.

-

little-endian

The little-endian ByteOrder.

+

java-prim-layout

Map of primitive type names to the Java types for a method handle.

+

little-endian

The little-endian ByteOrder.

See big-endian, native-endian

-

long-alignment

The alignment in bytes of a c-sized long.

-

long-layout

The MemoryLayout for a c-sized long in native-endian ByteOrder.

-

long-size

The size in bytes of a c-sized long.

-

native-endian

The ByteOrder for the native endianness of the current hardware.

+

long-alignment

The alignment in bytes of a c-sized long.

+

long-layout

The MemoryLayout for a c-sized long in native-endian ByteOrder.

+

long-size

The size in bytes of a c-sized long.

+

native-endian

The ByteOrder for the native endianness of the current hardware.

See big-endian, little-endian.

-

null

The NULL pointer object.

+

null

The NULL pointer object.

While this object is safe to pass to functions which serialize to a pointer, it’s generally encouraged to simply pass nil. This value primarily exists to make it easier to write custom types with a primitive pointer representation.

-

null?

(null? addr)

Checks if a memory address is null.

-

pointer-alignment

The alignment in bytes of a c-sized pointer.

-

pointer-layout

The MemoryLayout for a native pointer in native-endian ByteOrder.

-

pointer-size

The size in bytes of a c-sized pointer.

-

primitive-type

multimethod

Gets the primitive type that is used to pass as an argument for the type.

+

null?

(null? addr)

Checks if a memory address is null.

+

pointer-alignment

The alignment in bytes of a c-sized pointer.

+

pointer-layout

The MemoryLayout for a native pointer in native-endian ByteOrder.

+

pointer-size

The size in bytes of a c-sized pointer.

+

primitive-type

multimethod

Gets the primitive type that is used to pass as an argument for the type.

This is for objects which are passed to native functions as primitive types, but which need additional logic to be performed during serialization and deserialization.

Implementations of this method should take into account that type arguments may not always be evaluated before passing to this function.

Returns nil for any type which does not have a primitive representation.

-

primitive-types

A set of all primitive types.

-

primitive?

(primitive? type)

A predicate to determine if a given type is primitive.

-

read-address

(read-address segment)(read-address segment offset)

Reads an address from the segment, at an optional offset, wrapped in a MemorySegment.

-

read-byte

(read-byte segment)(read-byte segment offset)

Reads a byte from the segment, at an optional offset.

-

read-char

(read-char segment)(read-char segment offset)

Reads a char from the segment, at an optional offset.

-

read-double

(read-double segment)(read-double segment offset)(read-double segment offset byte-order)

Reads a double from the segment, at an optional offset.

+

primitive-types

A set of all primitive types.

+

primitive?

(primitive? type)

A predicate to determine if a given type is primitive.

+

read-address

(read-address segment)(read-address segment offset)

Reads an address from the segment, at an optional offset, wrapped in a MemorySegment.

+

read-byte

(read-byte segment)(read-byte segment offset)

Reads a byte from the segment, at an optional offset.

+

read-char

(read-char segment)(read-char segment offset)

Reads a char from the segment, at an optional offset.

+

read-double

(read-double segment)(read-double segment offset)(read-double segment offset byte-order)

Reads a double from the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

read-float

(read-float segment)(read-float segment offset)(read-float segment offset byte-order)

Reads a float from the segment, at an optional offset.

+

read-float

(read-float segment)(read-float segment offset)(read-float segment offset byte-order)

Reads a float from the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

read-int

(read-int segment)(read-int segment offset)(read-int segment offset byte-order)

Reads a int from the segment, at an optional offset.

+

read-int

(read-int segment)(read-int segment offset)(read-int segment offset byte-order)

Reads a int from the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

read-long

(read-long segment)(read-long segment offset)(read-long segment offset byte-order)

Reads a long from the segment, at an optional offset.

+

read-long

(read-long segment)(read-long segment offset)(read-long segment offset byte-order)

Reads a long from the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

read-short

(read-short segment)(read-short segment offset)(read-short segment offset byte-order)

Reads a short from the segment, at an optional offset.

+

read-short

(read-short segment)(read-short segment offset)(read-short segment offset byte-order)

Reads a short from the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

reinterpret

(reinterpret segment size)(reinterpret segment size arena)(reinterpret segment size arena cleanup)

Reinterprets the segment as having the passed size.

+

reinterpret

(reinterpret segment size)(reinterpret segment size arena)(reinterpret segment size arena cleanup)

Reinterprets the segment as having the passed size.

If arena is passed, the scope of the segment is associated with the arena, as well as its access constraints. If cleanup is passed, it will be a 1-argument function of a fresh memory segment backed by the same memory as the returned segment which should perform any required cleanup operations. It will be called when the arena is closed.

-

seq-of

(seq-of type segment)

Constructs a lazy sequence of type elements deserialized from segment.

-

serialize

(serialize obj type)(serialize obj type arena)

Serializes an arbitrary type.

+

seq-of

(seq-of type segment)

Constructs a lazy sequence of type elements deserialized from segment.

+

serialize

(serialize obj type)(serialize obj type arena)

Serializes an arbitrary type.

For types which have a primitive representation, this serializes into that representation. For types which do not, it allocates a new segment and serializes into that.

-

serialize*

multimethod

Constructs a serialized version of the obj and returns it.

+

serialize*

multimethod

Constructs a serialized version of the obj and returns it.

Any new allocations made during the serialization should be tied to the given arena, except in extenuating circumstances.

This method should only be implemented for types that serialize to primitives.

-

serialize-into

multimethod

Writes a serialized version of the obj to the given segment.

+

serialize-into

multimethod

Writes a serialized version of the obj to the given segment.

Any new allocations made during the serialization should be tied to the given arena, except in extenuating circumstances.

This method should be implemented for any type which does not override c-layout.

For any other type, this will serialize it as serialize* before writing the result value into the segment.

-

shared-arena

(shared-arena)

Constructs a new shared memory arena.

+

shared-arena

(shared-arena)

Constructs a new shared memory arena.

This arena can be shared across threads and memory allocated in it will only be cleaned up once any thread accessing the arena closes it.

-

short-alignment

The alignment in bytes of a c-sized short.

-

short-layout

The MemoryLayout for a c-sized short in native-endian ByteOrder.

-

short-size

The size in bytes of a c-sized short.

-

size-of

(size-of type)

The size in bytes of the given type.

-

slice

(slice segment offset)(slice segment offset size)

Get a slice over the segment with the given offset.

-

slice-segments

(slice-segments segment size)

Constructs a lazy seq of size-length memory segments, sliced from segment.

-

write-address

(write-address segment value)(write-address segment offset value)

Writes the address of the MemorySegment value to the segment, at an optional offset.

-

write-byte

(write-byte segment value)(write-byte segment offset value)

Writes a byte to the segment, at an optional offset.

-

write-char

(write-char segment value)(write-char segment offset value)

Writes a char to the segment, at an optional offset.

-

write-double

(write-double segment value)(write-double segment offset value)(write-double segment offset byte-order value)

Writes a double to the segment, at an optional offset.

+

short-alignment

The alignment in bytes of a c-sized short.

+

short-layout

The MemoryLayout for a c-sized short in native-endian ByteOrder.

+

short-size

The size in bytes of a c-sized short.

+

size-of

(size-of type)

The size in bytes of the given type.

+

slice

(slice segment offset)(slice segment offset size)

Get a slice over the segment with the given offset.

+

slice-segments

(slice-segments segment size)

Constructs a lazy seq of size-length memory segments, sliced from segment.

+

write-address

(write-address segment value)(write-address segment offset value)

Writes the address of the MemorySegment value to the segment, at an optional offset.

+

write-byte

(write-byte segment value)(write-byte segment offset value)

Writes a byte to the segment, at an optional offset.

+

write-char

(write-char segment value)(write-char segment offset value)

Writes a char to the segment, at an optional offset.

+

write-double

(write-double segment value)(write-double segment offset value)(write-double segment offset byte-order value)

Writes a double to the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

write-float

(write-float segment value)(write-float segment offset value)(write-float segment offset byte-order value)

Writes a float to the segment, at an optional offset.

+

write-float

(write-float segment value)(write-float segment offset value)(write-float segment offset byte-order value)

Writes a float to the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

write-int

(write-int segment value)(write-int segment offset value)(write-int segment offset byte-order value)

Writes a int to the segment, at an optional offset.

+

write-int

(write-int segment value)(write-int segment offset value)(write-int segment offset byte-order value)

Writes a int to the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

write-long

(write-long segment value)(write-long segment offset value)(write-long segment offset byte-order value)

Writes a long to the segment, at an optional offset.

+

write-long

(write-long segment value)(write-long segment offset value)(write-long segment offset byte-order value)

Writes a long to the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-

write-short

(write-short segment value)(write-short segment offset value)(write-short segment offset byte-order value)

Writes a short to the segment, at an optional offset.

+

write-short

(write-short segment value)(write-short segment offset value)(write-short segment offset byte-order value)

Writes a short to the segment, at an optional offset.

If byte-order is not provided, it defaults to native-endian.

-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 36ad180..0e9517c 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,6 +1,6 @@ -coffi v1.0.486

coffi v1.0.486

A Foreign Function Interface in Clojure for JDK 22+.

Namespaces

coffi.ffi

Functions for creating handles to native functions and loading native libraries.

+coffi v1.0.486

coffi v1.0.486

A Foreign Function Interface in Clojure for JDK 22+.

Topics

Namespaces

coffi.layout

Functions for adjusting the layout of structs.

Public variables and functions:

\ No newline at end of file