diff --git a/docs/01-Getting-Started.html b/docs/01-Getting-Started.html index b439600..b3ecc4a 100644 --- a/docs/01-Getting-Started.html +++ b/docs/01-Getting-Started.html @@ -1,7 +1,7 @@ Getting Started

Getting Started

-

Installation {#installation}

+

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"}
@@ -21,7 +21,7 @@ io.github.IGJoshua/coffi {:git/tag "x.y.z" :git/sha "abcdef0"}
 

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 {#usage}

+

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]])
@@ -48,7 +48,7 @@ io.github.IGJoshua/coffi {:git/tag "x.y.z" :git/sha "abcdef0"}
 

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 {#primitive-types}

+

Primitive Types

Coffi defines a basic set of primitive types:

  • byte
  • @@ -61,7 +61,7 @@ io.github.IGJoshua/coffi {:git/tag "x.y.z" :git/sha "abcdef0"}
  • 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 {#composite-types}

+

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;
@@ -117,14 +117,14 @@ Point zero(void) {
 

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 {#callbacks}

+

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 {#variadic-functions}

+

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))
 
@@ -136,7 +136,7 @@ Point zero(void) {

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 {#globals}

+

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)
@@ -154,7 +154,7 @@ Point zero(void) {
 

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.

-

Complex Wrappers {#complex-wrappers}

+

Complex Wrappers

Some functions require more complex code to map nicely to a Clojure function. The defcfn macro provides facilities to wrap the native function with some Clojure code to make this easier.

(defcfn takes-array
   "takes_array_with_count" [::mem/pointer ::mem/long] ::mem/void
diff --git a/docs/03-Builtin-Types.html b/docs/03-Builtin-Types.html
index c79370f..0222e5a 100644
--- a/docs/03-Builtin-Types.html
+++ b/docs/03-Builtin-Types.html
@@ -1,14 +1,13 @@
 
 Built-in Types **WIP**

Built-in Types WIP

-

TODO Primitives {#primitives}

-

TODO Arrays {#arrays}

-

TODO Pointers {#pointers}

-

TODO Structs {#structs}

-

TODO Enums {#enums}

-

TODO Flagsets {#flagsets}

-

TODO Functions {#functions}

-

Unions {#unions}

+

Primitives

+

Arrays

+

Pointers

+

Structs

+

Enums

+

Flagsets

+

Unions

Unions in coffi are rather limited. They can be serialized, but not deserialized without external information.

[::mem/union
  #{::mem/float ::mem/double}
@@ -16,7 +15,7 @@
              (float? %) ::mem/float
              (double? %) ::mem/double)]
 
-

This is a minimal union in coffi. If the :dispatch keyword argument is not passed, then the union cannot be serialized, as coffi would not know which type to serialize the values as. In the example with a tagged union, a dispatch function was not provided because the type was only used for the native layout.

+

This is a minimal union in coffi. If the :dispatch keyword argument is not passed, then the union cannot be serialized, as coffi would not know which type to serialize the values as. In the example with a tagged union, a dispatch function was not provided because the type was only used for the native layout.

In addition to a dispatch function, when serializing a union an extract function may also be provided. In the case of the value in the tagged union from before, it could be represented for serialization purposes like so:

[::mem/union
  #{::mem/int ::mem/c-string}
@@ -27,5 +26,5 @@
 

This union however would not include the tag when serialized.

If a union is deserialized, then all that coffi does is to allocate a new segment of the appropriate size with an implicit arena so that it may later be garbage collected, and copies the data from the source segment into it. It’s up to the user to call deserialize-from on that segment with the appropriate type.

-

TODO Raw Types {#raw-types}

+

Raw Types

\ No newline at end of file diff --git a/docs/04-Custom-Types.html b/docs/04-Custom-Types.html index f2d9537..3194169 100644 --- a/docs/04-Custom-Types.html +++ b/docs/04-Custom-Types.html @@ -3,7 +3,7 @@ Custom Types

Custom Types

Custom types with serializers and deserializers may be created. This is done using two sets of three multimethods which can be extended by the user. For any given type, only one set need be implemented.

Two examples of custom types are given here, one is a 3d vector, and the other an example of a tagged union.

-

Vector3 {#vector}

+

Vector3

For the vector type, it will serialize to a pointer to an array of three floats.

The multimethod primitive-type returns the primitive type that a given type serializes to. For this example, it should be a pointer.

(defmethod mem/primitive-type ::vector
@@ -32,7 +32,7 @@
         (deserialize ::vector))))
 

This function takes an arena and returns the deserialized vector, and it will free the pointer when the arena closes.

-

Tagged Union {#tagged-union}

+

Tagged Union

For the tagged union type, we will represent the value as a vector of a keyword naming the tag and the value. The type itself will need to take arguments, similar to struct. For example, if we were to represent a result type like in Rust, we might have the following values:

[:ok 5]
 [:err "Invalid number format"]
diff --git a/docs/05-Low-Level-Wrappers.html b/docs/05-Low-Level-Wrappers.html
index 0da1816..6539b51 100644
--- a/docs/05-Low-Level-Wrappers.html
+++ b/docs/05-Low-Level-Wrappers.html
@@ -1,7 +1,7 @@
 
 Low-Level Wrappers

Low-Level Wrappers

-

Unwrapped Native Handles {#unwrapped-native-handles}

+

Unwrapped Native Handles

Some native libraries work with handles to large amounts of data at once, making it undesirable to marshal data back and forth from Clojure, both because it’s not necessary to work with the data in Clojure directly, or also because of the high (de)serialization costs associated with marshaling. In cases like these, unwrapped native handles are desirable.

The functions make-downcall and make-varargs-factory are also provided to create raw function handles.

(def raw-strlen (ffi/make-downcall "strlen" [::mem/c-string] ::mem/long))
@@ -15,7 +15,7 @@
 

Clojure functions serialized to this type will have their arguments and return value exactly match the types specified and will not perform any serialization or deserialization at their boundaries.

One important caveat to consider when writing wrappers for performance-sensitive functions is that the convenience macro defcfn that coffi provides will already perform no serialization or deserialization on primitive arguments and return types, so for functions with only primitive argument and return types there is no performance reason to choose unwrapped native handles over the convenience macro.

-

Manual (De)Serialization {#manual-serdes}

+

Manual (De)Serialization

Coffi uses multimethods to dispatch to (de)serialization functions to enable code that’s generic over the types it operates on. However, in cases where you know the exact types that you will be (de)serializing and the multimethod dispatch overhead is too high a cost, it may be appropriate to manually handle (de)serializing data. This will often be done paired with Unwrapped Native Handles.

Convenience functions are provided to both read and write all primitive types and addresses, including byte order.

As an example, when wrapping a function that returns an array of big-endian floats, the following code might be used.

diff --git a/docs/99-Benchmarks.html b/docs/99-Benchmarks.html index 4d9dfc8..94fd620 100644 --- a/docs/99-Benchmarks.html +++ b/docs/99-Benchmarks.html @@ -5,7 +5,7 @@

An additional consideration when thinking about alternatives is the performance of each available option. It’s an established fact that JNA (used by all three alternative libraries on JDK <16) introduces more overhead when calling native code than JNI does.

In order to provide a benchmark to see how much of a difference the different native interfaces make, we can use criterium to benchmark each. GLFW’s glfwGetTime function will be used for the test as it performs a simple operation, and is conveniently already wrapped in JNI by the excellent LWJGL library.

The following benchmarks were run on a Lenovo Thinkpad with an Intel i7-10610U running Manjaro Linux, using Clojure 1.10.3 on Java 17.

-

JNI {#jni}

+

JNI

The baseline for performance is the JNI. Using LWJGL it’s relatively simple to benchmark. The following Clojure CLI command will start a repl with LWJGL and criterium loaded.

$ clj -Sdeps '{:deps {org.lwjgl/lwjgl {:mvn/version "3.2.3"}
                       org.lwjgl/lwjgl-glfw {:mvn/version "3.2.3"}
@@ -40,7 +40,7 @@ nil
 
user=> bench/estimated-overhead-cache
 6.400703613065185E-9
 
-

Coffi {#coffi}

+

Coffi

The dependencies when using coffi are simpler, but it also requires some JVM options to support the foreign access api.

$ clj -Sdeps '{:deps {org.suskalo/coffi {:mvn/version "0.1.205"}
                       criterium/criterium {:mvn/version "0.4.6"}}}' \
@@ -76,7 +76,7 @@ Execution time sample std-deviation : 1.598571 ns
 nil
 

This result is about 1.3 ns faster, and while that is less than the standard deviation of 1.6, it’s quite close to it.

-

Clojure-JNA {#clojure-jna}

+

Clojure-JNA

Clojure-JNA uses the JNA library, which was designed to provide Java with an easy way to access native libraries, but which is known for not having the greatest performance. Since this is an older project, I’m also including the clojure dependency to ensure the correct version is used.

$ clj -Sdeps '{:deps {org.clojure/clojure {:mvn/version "1.10.3"}
                       net.n01se/clojure-jna {:mvn/version "1.0.0"}
@@ -129,7 +129,7 @@ nil
 

This is much better, but is still about 3x slower than JNI, meaning the overhead from using JNA is still bigger than the function runtime.

This performance penalty is still small in the scope of longer-running functions, and so may not be a concern for your application, but it is something to be aware of.

-

tech.jna {#tech-jna}

+

tech.jna

The tech.jna library is similar in scope to Clojure-JNA, however was written to fit into an ecosystem of libraries meant for array-based programming for machine learning and data science.

$ clj -Sdeps '{:deps {techascent/tech.jna {:mvn/version "4.05"}
                       criterium/criterium {:mvn/version "0.4.6"}}}'
@@ -165,7 +165,7 @@ Execution time sample std-deviation : 14.557312 ns
 nil
 

This version is even slower than Clojure-JNA. I’m unsure where this overhead is coming from, but I’ll admit that I haven’t looked at their implementations very closely.

-

dtype-next {#dtype-next}

+

dtype-next

The library dtype-next replaced tech.jna in the toolkit of the group working on machine learning and array-based programming, and it includes support for composite data types including structs, as well as primitive functions and callbacks.

In addition, dtype-next has two different ffi backends. First is JNA, which is usable on any JDK version, and is what we’ll use for the first benchmark. Second is the Java 16 version of Project Panama, which will be shown next.

In order to use the dtype-next ffi with the JNA backend, the JNA library has to be included in the dependencies.

diff --git a/docs/articles/01-Getting-Started.md b/docs/articles/01-Getting-Started.md index fa63b38..1374b52 100644 --- a/docs/articles/01-Getting-Started.md +++ b/docs/articles/01-Getting-Started.md @@ -1,6 +1,6 @@ # Getting Started -## Installation {#installation} +## Installation This library is available on Clojars. Add one of the following entries to the `:deps` key of your `deps.edn`: @@ -49,7 +49,7 @@ 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 {#usage} +## 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. @@ -107,7 +107,7 @@ 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 {#primitive-types} +### Primitive Types Coffi defines a basic set of primitive types: - byte @@ -124,7 +124,7 @@ 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 {#composite-types} +### 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: @@ -213,7 +213,7 @@ in C. [::mem/array ::mem/int 3] ``` -### Callbacks {#callbacks} +### Callbacks In addition to these composite types, there is also support for Clojure functions. @@ -244,7 +244,7 @@ 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 {#variadic-functions} +### Variadic Functions Some native functions can take any number of arguments, and in these cases coffi provides `vacfn-factory` (for "varargs C function factory"). @@ -268,7 +268,7 @@ 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 {#globals} +### 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` @@ -309,7 +309,7 @@ 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. -### Complex Wrappers {#complex-wrappers} +### Complex Wrappers Some functions require more complex code to map nicely to a Clojure function. The `defcfn` macro provides facilities to wrap the native function with some Clojure code to make this easier. diff --git a/docs/articles/03-Builtin-Types.md b/docs/articles/03-Builtin-Types.md index 71663d3..03bb8c8 100644 --- a/docs/articles/03-Builtin-Types.md +++ b/docs/articles/03-Builtin-Types.md @@ -1,20 +1,18 @@ # Built-in Types **WIP** -### TODO Primitives {#primitives} +### Primitives -### TODO Arrays {#arrays} +### Arrays -### TODO Pointers {#pointers} +### Pointers -### TODO Structs {#structs} +### Structs -### TODO Enums {#enums} +### Enums -### TODO Flagsets {#flagsets} +### Flagsets -### TODO Functions {#functions} - -### Unions {#unions} +### Unions Unions in coffi are rather limited. They can be serialized, but not deserialized without external information. @@ -28,9 +26,8 @@ without external information. This is a minimal union in coffi. If the `:dispatch` keyword argument is not passed, then the union cannot be serialized, as coffi would not know which type -to serialize the values as. In [the example with a tagged -union](04-Custom-Types.md#tagged-union), a dispatch function was not provided -because the type was only used for the native layout. +to serialize the values as. In the example with a tagged union, a dispatch +function was not provided because the type was only used for the native layout. In addition to a dispatch function, when serializing a union an extract function may also be provided. In the case of the value in the tagged union from before, @@ -53,4 +50,4 @@ garbage collected, and copies the data from the source segment into it. It's up to the user to call `deserialize-from` on that segment with the appropriate type. -### TODO Raw Types {#raw-types} +### Raw Types diff --git a/docs/articles/04-Custom-Types.md b/docs/articles/04-Custom-Types.md index 5dfb509..e785d9d 100644 --- a/docs/articles/04-Custom-Types.md +++ b/docs/articles/04-Custom-Types.md @@ -6,7 +6,7 @@ given type, only one set need be implemented. Two examples of custom types are given here, one is a 3d vector, and the other an example of a tagged union. -### Vector3 {#vector} +### Vector3 For the vector type, it will serialize to a pointer to an array of three floats. The multimethod `primitive-type` returns the primitive type that a given type @@ -56,7 +56,7 @@ that takes a pointer exists, we could use this: This function takes an arena and returns the deserialized vector, and it will free the pointer when the arena closes. -### Tagged Union {#tagged-union} +### Tagged Union For the tagged union type, we will represent the value as a vector of a keyword naming the tag and the value. The type itself will need to take arguments, similar to `struct`. For example, if we were to represent a result type like in diff --git a/docs/articles/05-Low-Level-Wrappers.md b/docs/articles/05-Low-Level-Wrappers.md index c3855d0..e0f131f 100644 --- a/docs/articles/05-Low-Level-Wrappers.md +++ b/docs/articles/05-Low-Level-Wrappers.md @@ -1,6 +1,6 @@ # Low-Level Wrappers -### Unwrapped Native Handles {#unwrapped-native-handles} +### Unwrapped Native Handles Some native libraries work with handles to large amounts of data at once, making it undesirable to marshal data back and forth from Clojure, both because it's not necessary to work with the data in Clojure directly, or also because of the @@ -45,7 +45,7 @@ return types, so for functions with only primitive argument and return types there is no performance reason to choose unwrapped native handles over the convenience macro. -### Manual (De)Serialization {#manual-serdes} +### Manual (De)Serialization Coffi uses multimethods to dispatch to (de)serialization functions to enable code that's generic over the types it operates on. However, in cases where you know the exact types that you will be (de)serializing and the multimethod diff --git a/docs/articles/99-Benchmarks.md b/docs/articles/99-Benchmarks.md index a9b2b45..6e30eff 100644 --- a/docs/articles/99-Benchmarks.md +++ b/docs/articles/99-Benchmarks.md @@ -18,7 +18,7 @@ conveniently already wrapped in JNI by the excellent The following benchmarks were run on a Lenovo Thinkpad with an Intel i7-10610U running Manjaro Linux, using Clojure 1.10.3 on Java 17. -### JNI {#jni} +### JNI The baseline for performance is the JNI. Using LWJGL it's relatively simple to benchmark. The following Clojure CLI command will start a repl with LWJGL and criterium loaded. @@ -70,7 +70,7 @@ user=> bench/estimated-overhead-cache 6.400703613065185E-9 ``` -### Coffi {#coffi} +### Coffi The dependencies when using coffi are simpler, but it also requires some JVM options to support the foreign access api. @@ -117,7 +117,7 @@ nil This result is about 1.3 ns faster, and while that is less than the standard deviation of 1.6, it's quite close to it. -### Clojure-JNA {#clojure-jna} +### Clojure-JNA Clojure-JNA uses the JNA library, which was designed to provide Java with an easy way to access native libraries, but which is known for not having the greatest performance. Since this is an older project, I'm also including the @@ -192,7 +192,7 @@ This performance penalty is still small in the scope of longer-running functions, and so may not be a concern for your application, but it is something to be aware of. -### tech.jna {#tech-jna} +### tech.jna The tech.jna library is similar in scope to Clojure-JNA, however was written to fit into an ecosystem of libraries meant for array-based programming for machine learning and data science. @@ -242,7 +242,7 @@ This version is even slower than Clojure-JNA. I'm unsure where this overhead is coming from, but I'll admit that I haven't looked at their implementations very closely. -### dtype-next {#dtype-next} +### dtype-next The library dtype-next replaced tech.jna in the toolkit of the group working on machine learning and array-based programming, and it includes support for composite data types including structs, as well as primitive functions and diff --git a/docs/coffi.ffi.html b/docs/coffi.ffi.html index 9a14583..975a489 100644 --- a/docs/coffi.ffi.html +++ b/docs/coffi.ffi.html @@ -4,38 +4,38 @@

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 d9bc30e..aaca13e 100644 --- a/docs/coffi.layout.html +++ b/docs/coffi.layout.html @@ -3,4 +3,4 @@ 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 9b24faa..b8f16b4 100644 --- a/docs/coffi.mem.html +++ b/docs/coffi.mem.html @@ -5,117 +5,117 @@

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