Module Ctypes
The core ctypes module.
The main points of interest are the set of functions for describing C types (see types) and the set of functions for accessing C values (see Values representing C values). The Foreign.foreign function uses C type descriptions to bind external C values.
Pointer types
type ('a, 'b) pointer= ('a, 'b) Ctypes_static.pointerThe type of pointer values. A value of type
('a, [`C]) pointercontains a C-compatible pointer, and a value of type('a, [`OCaml]) pointercontains a pointer to a value that can be moved by OCaml runtime.
C-compatible pointers
type 'a ptr= ('a, [ `C ]) pointerThe type of C-compatible pointer values. A value of type
t ptrcan be used to read and write values of typetat particular addresses.
type 'a ocaml= 'a Ctypes_static.ocamlThe type of pointer values pointing directly into OCaml values. Pointers of this type should never be captured by external code. In particular, functions accepting
'a ocamlpointers must not invoke any OCaml code.
C array types
type 'a carray= 'a Ctypes_static.carrayThe type of C array values. A value of type
t carraycan be used to read and write array objects in C-managed storage.
Bigarray types
type 'a bigarray_class= 'a Ctypes_static.bigarray_classThe type of Bigarray classes. There are four instances, one for each of the Bigarray submodules.
val genarray : < element : 'a; layout : 'l; ba_repr : 'b; bigarray : ('a, 'b, 'l) Bigarray.Genarray.t; carray : 'a carray; dims : int array; > bigarray_classThe class of
Bigarray.Genarray.tvalues
val array1 : < element : 'a; layout : 'l; ba_repr : 'b; bigarray : ('a, 'b, 'l) Bigarray.Array1.t; carray : 'a carray; dims : int; > bigarray_classThe class of
Bigarray.Array1.tvalues
val array2 : < element : 'a; layout : 'l; ba_repr : 'b; bigarray : ('a, 'b, 'l) Bigarray.Array2.t; carray : 'a carray carray; dims : int * int; > bigarray_classThe class of
Bigarray.Array2.tvalues
val array3 : < element : 'a; layout : 'l; ba_repr : 'b; bigarray : ('a, 'b, 'l) Bigarray.Array3.t; carray : 'a carray carray carray; dims : int * int * int; > bigarray_classThe class of
Bigarray.Array3.tvalues
Struct and union types
type ('a, 'kind) structured= ('a, 'kind) Ctypes_static.structuredThe base type of values representing C struct and union types. The
'kindparameter is a polymorphic variant type indicating whether the type represents a struct (`Struct) or a union (`Union).
type 'a structure= ('a, [ `Struct ]) structuredThe type of values representing C struct types.
type 'a union= ('a, [ `Union ]) structuredThe type of values representing C union types.
type ('a, 't) field= ('a, 't) Ctypes_static.fieldThe type of values representing C struct or union members (called "fields" here). A value of type
(a, s) fieldrepresents a field of typeain a struct or union of types.
type 'a abstract= 'a Ctypes_static.abstractThe type of abstract values. The purpose of the
abstracttype is to represent values whose type varies from platform to platform.For example, the type
pthread_tis a pointer on some platforms, an integer on other platforms, and a struct on a third set of platforms. One way to deal with this kind of situation is to have possibly-platform-specific code which interrogates the C type in some way to help determine an appropriate representation. Another way is to useabstract, leaving the representation opaque.(Note, however, that although
pthread_tis a convenient example, since the type used to implement it varies significantly across platforms, it's not actually a good match forabstract, since values of typepthread_tare passed and returned by value.)
include Ctypes_types.TYPE with type 'a typ = 'a Ctypes_static.typ and type ('a, 's) field := ('a, 's) field
type 'a typ= 'a Ctypes_static.typThe type of values representing C types. There are two types associated with each
typvalue: the C type used to store and pass values, and the corresponding OCaml type. The type parameter indicates the OCaml type, so a value of typet typis used to read and write OCaml values of typet. There are various uses oftypvalues, including- constructing function types for binding native functions using
Foreign.foreign
- constructing pointers for reading and writing locations in C-managed storage using
ptr
- constructing function types for binding native functions using
The void type
val void : unit typValue representing the C void type. Void values appear in OCaml as the unit type, so using void in an argument or result type specification produces a function which accepts or returns unit.
Dereferencing a pointer to void is an error, as in C, and will raise
IncompleteType.
Scalar types
The scalar types consist of the Arithmetic types and the Pointer types.
Arithmetic types
The arithmetic types consist of the signed and unsigned integer types (including character types) and the floating types. There are values representing both exact-width integer types (of 8, 16, 32 and 64 bits) and types whose size depend on the platform (signed and unsigned short, int, long, long long).
val char : char typValue representing the C type
char.
Signed integer types
val schar : int typValue representing the C type
signed char.
val short : int typValue representing the C type (
signed)short.
val int : int typValue representing the C type (
signed)int.
val long : Signed.long typValue representing the C type (
signed)long.
val llong : Signed.llong typValue representing the C type (
signed)long long.
val nativeint : nativeint typValue representing the C type (
signed)int.
val int8_t : int typValue representing an 8-bit signed integer C type.
val int16_t : int typValue representing a 16-bit signed integer C type.
val int32_t : int32 typValue representing a 32-bit signed integer C type.
val int64_t : int64 typValue representing a 64-bit signed integer C type.
val camlint : int typValue representing an integer type with the same storage requirements as an OCaml
int.
Unsigned integer types
val uchar : Unsigned.uchar typValue representing the C type
unsigned char.
val bool : bool typValue representing the C type
bool.
val uint8_t : Unsigned.uint8 typValue representing an 8-bit unsigned integer C type.
val uint16_t : Unsigned.uint16 typValue representing a 16-bit unsigned integer C type.
val uint32_t : Unsigned.uint32 typValue representing a 32-bit unsigned integer C type.
val uint64_t : Unsigned.uint64 typValue representing a 64-bit unsigned integer C type.
val size_t : Unsigned.size_t typValue representing the C type
size_t, an alias for one of the unsigned integer types. The actual size and alignment requirements forsize_tvary between platforms.
val ushort : Unsigned.ushort typValue representing the C type
unsigned short.
val sint : Signed.sint typValue representing the C type
int.
val uint : Unsigned.uint typValue representing the C type
unsigned int.
val ulong : Unsigned.ulong typValue representing the C type
unsigned long.
val ullong : Unsigned.ullong typValue representing the C type
unsigned long long.
module Uintptr : Unsigned.SFloating types
val float : float typValue representing the C single-precision
floattype.
val double : float typValue representing the C type
double.
Complex types
val complex32 : Stdlib.Complex.t typValue representing the C99 single-precision
float complextype.
val complex64 : Stdlib.Complex.t typValue representing the C99 double-precision
double complextype.
val complexld : ComplexL.t typValue representing the C99 long-double-precision
long double complextype.
Pointer types
C-compatible pointers
val ptr : 'a typ -> 'a Ctypes_static.ptr typConstruct a pointer type from an existing type (called the reference type).
val ptr_opt : 'a typ -> 'a Ctypes_static.ptr option typConstruct a pointer type from an existing type (called the reference type). This behaves like
ptr, except that null pointers appear in OCaml asNone.
val string : string typA high-level representation of the string type.
On the C side this behaves like
char *; on the OCaml side values read and written usingstringare simply native OCaml strings.To avoid problems with the garbage collector, values passed using
stringare copied into immovable C-managed storage before being passed to C.When the memory is not owned by the C code, -- i.e. when creating or initializing a struct in OCaml before passing it to C -- then the
stringview isn't a good choice, because there's no way to manage the lifetime of the C copy of the generated OCaml string.
OCaml pointers
val ocaml_string : string Ctypes_static.ocaml typValue representing the directly mapped storage of an OCaml string.
val ocaml_bytes : Stdlib.Bytes.t Ctypes_static.ocaml typValue representing the directly mapped storage of an OCaml byte array.
Array types
C array types
val array : int -> 'a typ -> 'a Ctypes_static.carray typConstruct a sized array type from a length and an existing type (called the element type).
Bigarray types
val bigarray : < element : 'a; layout : Bigarray.c_layout; ba_repr : 'b; dims : 'dims; bigarray : 'bigarray; carray : _; > Ctypes_static.bigarray_class -> 'dims -> ('a, 'b) Bigarray.kind -> 'bigarray typConstruct a sized C-layout bigarray type representation from a bigarray class, the dimensions, and the
Bigarray.kind.
val fortran_bigarray : < element : 'a; layout : Bigarray.fortran_layout; ba_repr : 'b; dims : 'dims; bigarray : 'bigarray; carray : _; > Ctypes_static.bigarray_class -> 'dims -> ('a, 'b) Bigarray.kind -> 'bigarray typConstruct a sized Fortran-layout bigarray type representation from a bigarray class, the dimensions, and the
Bigarray.kind.
val typ_of_bigarray_kind : ('a, 'b) Bigarray.kind -> 'a typtyp_of_bigarray_kind kis the type corresponding to the Bigarray kindk.
Struct and union types
val structure : string -> 's Ctypes_static.structure typConstruct a new structure type. The type value returned is incomplete and can be updated using
fielduntil it is passed toseal, at which point the set of fields is fixed.The type (
'_s structure typ) of the expression returned by the callstructure tagincludes a weak type variable, which can be explicitly instantiated to ensure that the OCaml values representing different C structure types have incompatible types. Typical usage is as follows:type tagnamelet tagname : tagname structure typ = structure "tagname"
val union : string -> 's Ctypes_static.union typConstruct a new union type. This behaves analogously to
structure; fields are added withfield.
val field : 't typ -> string -> 'a typ -> ('a, ('s, [< `Struct | `Union ]) Ctypes_static.structured as t) fieldfield ty label ty'adds a field of typety'with labellabelto the structure or union typetyand returns a field value that can be used to read and write the field in structure or union instances (e.g. usinggetfandsetf).Attempting to add a field to a union type that has been sealed with
sealis an error, and will raiseModifyingSealedType.
val seal : (_, [< `Struct | `Union ]) Ctypes_static.structured typ -> unitseal tcompletes the struct or union typetso that no further fields can be added. Struct and union types must be sealed before they can be used in a way that involves their size or alignment; see the documentation forIncompleteTypefor further details.
View types
val view : ?format_typ:((Stdlib.Format.formatter -> unit) -> Stdlib.Format.formatter -> unit) -> ?format:(Stdlib.Format.formatter -> 'b -> unit) -> read:('a -> 'b) -> write:('b -> 'a) -> 'a typ -> 'b typview ~read:r ~write:w tcreates a C type representationt'which behaves liketexcept that values read usingt'are subsequently transformed using the functionrand values written usingt'are first transformed using the functionw.For example, given suitable definitions of
string_of_char_ptrandchar_ptr_of_string, the type representationview ~read:string_of_char_ptr ~write:char_ptr_of_string (ptr char)can be used to pass OCaml strings directly to and from bound C functions, or to read and write string members in structs and arrays. (In fact, the
stringtype representation is defined in exactly this way.)The optional argument
format_typis used by theCtypes.format_typandstring_of_typfunctions to print the type at the top level and elsewhere. Ifformat_typis not supplied the printer fortis used instead.The optional argument
formatis used by theCtypes.formatandstring_offunctions to print the values. Ifformat_valis not supplied the printer fortis used instead.
Abstract types
val abstract : name:string -> size:int -> alignment:int -> 'a Ctypes_static.abstract typCreate an abstract type specification from the size and alignment requirements for the type.
Injection of concrete types
val lift_typ : 'a Ctypes_static.typ -> 'a typlift_typ tturns a concrete type representation into an abstract type representation.For example, retrieving struct layout from C involves working with an abstract representation of types which do not support operations such as
sizeof. Thelift_typfunction makes it possible to use concrete type representations wherever such abstract type representations are needed.
Function types
type 'a fn= 'a Ctypes_static.fnThe type of values representing C function types. A value of type
t fncan be used to bind to C functions and to describe type of OCaml functions passed to C.
val (@->) : 'a typ -> 'b fn -> ('a -> 'b) fnConstruct a function type from a type and an existing function type. This corresponds to prepending a parameter to a C function parameter list. For example,
int @-> ptr void @-> returning floatdescribes a function type that accepts two arguments -- an integer and a pointer to void -- and returns a float.
val returning : 'a typ -> 'a fnGive the return type of a C function. Note that
returningis intended to be used together with(@->); see the documentation for(@->)for an example.
type 'a static_funptr= 'a Ctypes_static.static_funptrFunction pointer types
The type of values representing C function pointer types.
val static_funptr : 'a fn -> 'a Ctypes_static.static_funptr typConstruct a function pointer type from an existing function type (called the reference type).
Operations on types
val sizeof : 'a typ -> intsizeof tcomputes the size in bytes of the typet. The exceptionIncompleteTypeis raised iftis incomplete.
val alignment : 'a typ -> intalignment tcomputes the alignment requirements of the typet. The exceptionIncompleteTypeis raised iftis incomplete.
val format_typ : ?name:string -> Stdlib.Format.formatter -> 'a typ -> unitPretty-print a C representation of the type to the specified formatter.
val format_fn : ?name:string -> Stdlib.Format.formatter -> 'a fn -> unitPretty-print a C representation of the function type to the specified formatter.
val string_of_typ : ?name:string -> 'a typ -> stringReturn a C representation of the type.
val string_of_fn : ?name:string -> 'a fn -> stringReturn a C representation of the function type.
Values representing C values
val format : 'a typ -> Stdlib.Format.formatter -> 'a -> unitPretty-print a representation of the C value to the specified formatter.
val string_of : 'a typ -> 'a -> stringReturn a string representation of the C value.
Pointer values
val null : unit ptrA null pointer.
val (!@) : 'a ptr -> 'a!@ pdereferences the pointerp. If the reference type is a scalar type then dereferencing constructs a new value. If the reference type is an aggregate type then dereferencing returns a value that references the memory pointed to byp.
val (<-@) : 'a ptr -> 'a -> unitp <-@ vwrites the valuevto the addressp.
val (+@) : ('a, 'b) pointer -> int -> ('a, 'b) pointerIf
pis a pointer to an array element thenp +@ ncomputes the address of thenth next element.
val (-@) : ('a, 'b) pointer -> int -> ('a, 'b) pointerIf
pis a pointer to an array element thenp -@ ncomputes the address of the nth previous element.
val ptr_diff : ('a, 'b) pointer -> ('a, 'b) pointer -> intptr_diff p qcomputesq - p. As in C, bothpandqmust point into the same array, and the result value is the difference of the subscripts of the two array elements.
val allocate : ?finalise:('a ptr -> unit) -> 'a typ -> 'a -> 'a ptrallocate t vallocates a fresh value of typet, initialises it withvand returns its address. The argument?finalise, if present, will be called just before the memory is freed. The value will be automatically freed after no references to the pointer remain within the calling OCaml program.
val allocate_n : ?finalise:('a ptr -> unit) -> 'a typ -> count:int -> 'a ptrallocate_n t ~count:nallocates a fresh array with element typetand lengthn, and returns its address. The argument?finalise, if present, will be called just before the memory is freed. The array will be automatically freed after no references to the pointer remain within the calling OCaml program. The memory is allocated with libc'scallocand is guaranteed to be zero-filled.
val ptr_compare : 'a ptr -> 'a ptr -> intIf
pandqare pointers to elementsiandjof the same array thenptr_compare p qcompares the indexes of the elements. The result is negative ifiis less thanj, positive ifiis greater thanj, and zero ifiandjare equal.
val is_null : 'a ptr -> boolis_null pis true whenpis a null pointer.
val ptr_of_raw_address : nativeint -> unit ptrConvert the numeric representation of an address to a pointer
val funptr_of_raw_address : nativeint -> (unit -> unit) Ctypes_static.static_funptrConvert the numeric representation of an address to a function pointer
val raw_address_of_ptr : unit ptr -> nativeintraw_address_of_ptr preturns the numeric representation of p.Note that the return value remains valid only as long as the pointed-to object is alive. If
pis a managed object (e.g. a value returned bymake) then unless the caller retains a reference top, the object may be collected, invalidating the returned address.
val string_from_ptr : char ptr -> length:int -> stringstring_from_ptr p ~lengthcreates a string initialized with thelengthcharacters at addressp.Raise
Invalid_argument "Ctypes.string_from_ptr"iflengthis negative.
val ocaml_string_start : string -> string ocamlocaml_string_start sallows to pass a pointer to the contents of an OCaml string directly to a C function.
val ocaml_bytes_start : Stdlib.Bytes.t -> Stdlib.Bytes.t ocamlocaml_bytes_start sallows to pass a pointer to the contents of an OCaml byte array directly to a C function.
Array values
C array values
module CArray : sig ... endOperations on C arrays.
Bigarray values
val bigarray_start : < element : 'a; layout : 'l; ba_repr : _; bigarray : 'b; carray : _; dims : _; > bigarray_class -> 'b -> 'a ptrReturn the address of the first element of the given Bigarray value.
val bigarray_of_ptr : < element : 'a; layout : Bigarray.c_layout; ba_repr : 'f; bigarray : 'b; carray : _; dims : 'i; > bigarray_class -> 'i -> ('a, 'f) Bigarray.kind -> 'a ptr -> 'bbigarray_of_ptr c dims k pconverts the C pointerpto a C-layout bigarray value. No copy is made; the bigarray references the memory pointed to byp.
val fortran_bigarray_of_ptr : < element : 'a; layout : Bigarray.fortran_layout; ba_repr : 'f; bigarray : 'b; carray : _; dims : 'i; > bigarray_class -> 'i -> ('a, 'f) Bigarray.kind -> 'a ptr -> 'bfortran_bigarray_of_ptr c dims k pconverts the C pointerpto a Fortran-layout bigarray value. No copy is made; the bigarray references the memory pointed to byp.
val array_of_bigarray : < element : _; layout : Bigarray.c_layout; ba_repr : _; bigarray : 'b; carray : 'c; dims : _; > bigarray_class -> 'b -> 'carray_of_bigarray c bconverts the bigarray valuebto a value of typeCArray.t. No copy is made; the result occupies the same memory asb.
val bigarray_of_array : < element : 'a; layout : Bigarray.c_layout; ba_repr : 'f; bigarray : 'b; carray : 'c carray; dims : 'i; > bigarray_class -> ('a, 'f) Bigarray.kind -> 'c carray -> 'bbigarray_of_array c k aconverts theCArray.tvalueato a C-layout bigarray value. No copy is made; the result occupies the same memory asa.
Struct and union values
val make : ?finalise:('s -> unit) -> (_, _) structured as s typ -> 'sAllocate a fresh, uninitialised structure or union value. The argument
?finalise, if present, will be called just before the underlying memory is freed.
val setf : (_, _) structured as s -> ('a, 's) field -> 'a -> unitsetf s f voverwrites the value of the fieldfin the structure or unionswithv.
val getf : (_, _) structured as s -> ('a, 's) field -> 'agetf s fretrieves the value of the fieldfin the structure or unions. The semantics for non-scalar types are non-copying, as for(!@).
val (@.) : (_, _) structured as s -> ('a, 's) field -> 'a ptrs @. fcomputes the address of the fieldfin the structure or union values.
val (|->) : (_, _) structured as s ptr -> ('a, 's) field -> 'a ptrp |-> fcomputes the address of the fieldfin the structure or union value pointed to byp.
val offsetof : (_, _ structure) field -> intoffsetof freturns the offset, in bytes, of the fieldffrom the beginning of the associated struct type.
val field_name : (_, _) field -> stringfield_name freturns the name of the fieldf.
val addr : (_, _) structured as s -> 's ptraddr sreturns the address of the structure or unions.
Coercions
val coerce : 'a typ -> 'b typ -> 'a -> 'bcoerce t1 t2returns a coercion function between the types represented byt1andt2. Ift1cannot be coerced tot2,coerceraisesUncoercible.The following coercions are currently supported:
- All function and object pointer types are intercoercible.
- Any type may be coerced to
void - There is a coercion between a
viewand another typet(in either direction) if there is a coercion between the representation type underlying the view andt. - Coercion is transitive: if
t1is coercible tot2andt2is coercible tot3, thent1is directly coercible tot3.
The set of supported coercions is subject to change. Future versions of ctypes may both add new types of coercion and restrict the existing coercions.
val coerce_fn : 'a fn -> 'b fn -> 'a -> 'bcoerce_fn f1 f2returns a coercion function between the function types represented byf1andf2. Iff1cannot be coerced tof2,coerce_fnraisesUncoercible.A function type
f1may be coerced to another function typef2if all of the following hold:- the C types described by
f1andf2have the same arity
- each argument of
f2may be coerced to the corresponding argument off1
- the return type of
f1may be coerced to the return type off2
The set of supported coercions is subject to change. Future versions of ctypes may both add new types of coercion and restrict the existing coercions.
- the C types described by
binding interfaces
.
module type FOREIGN = sig ... endForeign function binding interface.
module type TYPE = sig ... endForeign types binding interface.
module Root : sig ... end
Exceptions
exceptionUnsupported of stringAn attempt was made to use a feature not currently supported by ctypes. In practice this refers to attempts to use an union, array or abstract type as an argument or return type of a function.
exceptionModifyingSealedType of stringAn attempt was made to modify a sealed struct or union type description.
exceptionIncompleteTypeAn attempt was made to compute the size or alignment of an incomplete type.
The incomplete types are struct and union types that have not been sealed, and the void type.
It is not permitted to compute the size or alignment requirements of an incomplete type, to use it as a struct or union member, to read or write a value of the type through a pointer or to use it as the referenced type in pointer arithmetic. Additionally, incomplete struct and union types cannot be used as argument or return types.
exceptionUncoercible of uncoercible_infoAn attempt was made to coerce between uncoercible types.