Engee documentation

The C interface

@ccall library.function_name(argvalue1::argtype1, ...)::returntype
@ccall function_name(argvalue1::argtype1, ...)::returntype
@ccall $function_pointer(argvalue1::argtype1, ...)::returntype

Calls a function in a shared library exported from C, specified using library.function_name, where library is a string constant or literal. The library can be omitted, in which case function_name is resolved in the current process. In addition, you can also use @ccall to call the function pointer $function_pointer, for example, returned by `dlsym'.

Each argvalue for @ccall is converted to the corresponding argtype by automatically inserting calls to unsafe_convert(argtype, cconvert(argtype, argvalue)). (For more information, see the documentation on unsafe_convert and cconvert.) In most cases, this simply results in a call to `convert(argtype, argvalue)'.

Examples

@ccall strlen(s::Cstring)::Csize_t

The standard library function is called here with

size_t strlen(char *)

with the Julia variable named s. See also the description of `ccall'.

Varargs are supported with the following convention.

@ccall printf("%s = %d"::Cstring ; "foo"::Cstring, foo::Cint)::Cint

A semicolon is used to separate the required arguments (which must be at least one) from the variable number of arguments.

An example of using an external library:

# Сигнатура C для g_uri_escape_string:
# char *g_uri_escape_string(const char *unescaped, const char *reserved_chars_allowed, gboolean allow_utf8);

const glib = "libglib-2.0"
@ccall glib.g_uri_escape_string(my_uri::Cstring, ":/"::Cstring, true::Cint)::Cstring

If necessary, you can use a string literal immediately before the function name "libglib-2.0".g_uri_escape_string(....

ccall((function_name, library), returntype, (argtype1, ...), argvalue1, ...)
ccall(function_name, returntype, (argtype1, ...), argvalue1, ...)
ccall(function_pointer, returntype, (argtype1, ...), argvalue1, ...)

Calls a function in a shared library exported from C, specified using the tuple (function_name, library), where each component is a string or character. You can not specify a library, but use the character or string function_name, which are resolved in the current process. In addition, you can also use ccall to call the function pointer function_pointer, for example, returned by `dlsym'.

Note that the tuple of the argument type must be a literal tuple, not a variable or expression with the tuple value.

Each argvalue for ccall is converted to the corresponding argtype by automatically inserting calls to 'unsafe_convert(argtype, cconvert(argtype, argvalue)). (For more information, see the documentation on `unsafe_convert and cconvert.) In most cases, this simply results in a call to `convert(argtype, argvalue)'.

cglobal((symbol, library) [, type=Cvoid])

Gets a pointer to a global variable in a shared library exported from C, specified explicitly as in ccall. Returns Ptr{Type}. By default, Ptr' is used.{Cvoid} if the Type argument is not specified. Values can be read or written using respectively unsafe load or unsafe_store!.

@cfunction(callable, ReturnType, (ArgumentTypes...,)) -> Ptr{Cvoid}
@cfunction($callable, ReturnType, (ArgumentTypes...,)) -> CFunction

Creates a C-enabled function pointer from the Julia callable function for the specified type signature. To pass the return value to ccall, use the Ptr' argument type in the signature.{Cvoid}.

Note that an argument type tuple must be a literal tuple, not a variable or expression with a tuple value (although it may contain an expression with a symbol), and that these arguments will be evaluated in the global scope at compile time (and not deferred to runtime). Adding $ before the function argument causes the runtime environment to be changed instead of closed for the local variable callable (not supported in all architectures).

Examples

julia> function foo(x::Int, y::Int)
           return x + y
       end

julia> @cfunction(foo, Int, (Int, Int))
Ptr{Cvoid} @0x000000001b82fcd0
CFunction struct

Garbage collection descriptor for the return value from @cfunction when the first argument is annotated with $. Like all cfunction descriptors, it must be passed to ccall as Ptr'.{Cvoid}, and is automatically converted to the appropriate type at the call location.

See the description @cfunction.

unsafe_convert(T, x)

Converts x to a C argument of type T, where the input x should be the return value cconvert(T,...).

In cases where convert it is necessary to take the Julia object and convert it to Ptr, this function should be used to define and perform such a conversion.

Make sure that Julia’s reference to x exists for the entire duration of using the result of this function. Accordingly, the argument x of this function should never be an expression. It should only be a variable name or a field reference. For example, x=a.b.c' is a valid option, but `x=[a,b,c] is not.

The prefix unsafe in this function indicates that using the result of this function after its argument x is no longer available to the program may result in undefined behavior, including program corruption or crash at a later time.

See also the description cconvert.

cconvert(T,x)

Converts x to a value passed to the C code as type `T', usually by calling `convert(T, x)'.

In cases where x cannot be safely converted to T, cconvert', unlike `convert, can return an object of a type other than T, which, nevertheless, is suitable for processing by the function unsafe_convert. The result of this function should remain valid (for garbage collection) as long as the result unsafe_convert will no longer be needed. This can be used to allocate memory that will be accessed by `ccall'. If you need to select multiple objects, you can use a tuple of objects as the return value.

Neither convert nor cconvert should take a Julia object and convert it to `Ptr'.

unsafe_load(p::Ptr{T}, i::Integer=1)
unsafe_load(p::Ptr{T}, order::Symbol)
unsafe_load(p::Ptr{T}, i::Integer, order::Symbol)

Loads a value of type T from the address of the i’th element (indexed from 1), starting with `p'. It is equivalent to the expression C `p[i-1]. If necessary, atomic memory ordering can be provided.

The prefix `unsafe' in this function indicates that the check ensuring the validity of the pointer `p' is not performed. As in C, the programmer is responsible for ensuring that when this function is called, the memory referenced is not freed and garbage is not collected. Improper use may cause the program to crash or return "junk" responses. Unlike in C, dereference of a memory area allocated as a different type can be correct, provided that these types are compatible.

Compatibility: Julia 1.10

The 'order` argument was first implemented in Julia 1.10.

See also the description atomic.

unsafe_store!(p::Ptr{T}, x, i::Integer=1)
unsafe_store!(p::Ptr{T}, x, order::Symbol)
unsafe_store!(p::Ptr{T}, x, i::Integer, order::Symbol)

Stores a value of type T at the address of the i’th element (indexed from 1), starting with `p'. It is equivalent to the expression C `p[i-1] = x. If necessary, atomic memory ordering can be provided.

The prefix `unsafe' in this function indicates that the check ensuring the validity of the pointer `p' is not performed. As in C, the programmer is responsible for ensuring that when this function is called, the memory referenced is not freed and garbage is not collected. Improper use may cause the program to crash. Unlike in C, storing a memory area allocated as a different type can be correct, provided that these types are compatible.

Compatibility: Julia 1.10

The 'order` argument was first implemented in Julia 1.10.

See also the description atomic.

unsafe_modify!(p::Ptr{T}, op, x, [order::Symbol]) -> Pair

The operations of obtaining and specifying the memory address are performed atomically after applying the op function. If such a feature (for example, atomic increment) is supported by the hardware, operations can be optimized using the appropriate hardware instruction. Otherwise, the execution will happen like this:

y = unsafe_load(p) z = op(y, x) unsafe_store!(p, z) return y => z

The prefix `unsafe' in this function indicates that the check ensuring the validity of the pointer `p' is not performed. As in C, the programmer is responsible for ensuring that when this function is called, the memory referenced is not freed and garbage is not collected. Improper use may cause the program to crash.

Compatibility: Julia 1.10

This feature requires a version of Julia at least 1.10.

See also the description modifyproperty!, atomic

unsafe_replace!(p::Ptr{T}, expected, desired,
                [success_order::Symbol[, fail_order::Symbol=success_order]]) -> (; old, success::Bool)

The operations of obtaining the memory address and conditionally assigning the specified value to it are performed atomically. If this capability is supported by the hardware, operations can be optimized using the appropriate hardware instruction. Otherwise, the execution will happen like this:

y = unsafe_load(p, fail_order) ok = y === expected if ok unsafe_store!(p, desired, success_order) end return (; old = y, success = ok)

The prefix `unsafe' in this function indicates that the check ensuring the validity of the pointer `p' is not performed. As in C, the programmer is responsible for ensuring that when this function is called, the memory referenced is not freed and garbage is not collected. Improper use may cause the program to crash.

Compatibility: Julia 1.10

This feature requires a version of Julia at least 1.10.

See also the description replaceproperty!, atomic

unsafe_swap!(p::Ptr{T}, x, [order::Symbol])

The operations of simultaneously obtaining and specifying a memory address are performed atomically. If this capability is supported by the hardware, operations can be optimized using the appropriate hardware instruction. Otherwise, the execution will happen like this:

y = unsafe_load(p) unsafe_store!(p, x) return y

The prefix `unsafe' in this function indicates that the check ensuring the validity of the pointer `p' is not performed. As in C, the programmer is responsible for ensuring that when this function is called, the memory referenced is not freed and garbage is not collected. Improper use may cause the program to crash.

Compatibility: Julia 1.10

This feature requires a version of Julia at least 1.10.

See also the description swapproperty!, atomic

unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, N)

Copies N elements from the source pointer to the destination without checking. The size of the element is determined by the type of pointers.

The prefix unsafe' in this function indicates that the validation to ensure the validity of the `dest and src pointers is not performed. Improper use can lead to program corruption or crash, just like in C.

unsafe_copyto!(dest::Array, do, src::Array, so, N)

Copies N elements from the source array to the destination, starting with the linear index so at the source and do at the destination (indexed from 1).

The prefix `unsafe' in this function indicates that the check to ensure that N is within the boundaries of any array is not performed. Improper use can lead to program corruption or crash, just like in C.

copyto!(B::AbstractMatrix, ir_dest::AbstractUnitRange, jr_dest::AbstractUnitRange,
        tM::AbstractChar,
        M::AbstractVecOrMat, ir_src::AbstractUnitRange, jr_src::AbstractUnitRange) -> B

Effectively copies the elements of the matrix M to B, taking into account the symbolic parameter tM as follows:

tM Destination A source

B[ir_dest, jr_dest]

M[ir_src, jr_src]

B[ir_dest, jr_dest]

transpose(M)[ir_src, jr_src]

B[ir_dest, jr_dest]

adjoint(M)[ir_src, jr_src]

The elements B[ir_dest, jr_dest] are overwritten. In addition, the index range parameters must meet the conditions length(ir_dest) == length(ir_src) and length(jr_dest) == length(jr_src).

See also the description copy_transpose! and copy_adjoint!.


copyto!(dest::AbstractMatrix, src::UniformScaling)

Copies UniformScaling to the matrix.

Compatibility: Julia 1.1

In Julia 1.0, this method supported only a square destination matrix. In Julia 1.1. rectangular matrix support has been added.


copyto!(dest, do, src, so, N)

Copies N elements from the src collection starting from the linear index so to the dest array starting from the index do. Returns `dest'.


copyto!(dest::AbstractArray, src) -> dest

Copies all the elements from the src collection to the dest array, the length of which must be greater than or equal to the length of n for src. The first n elements of dest are overwritten, the rest are not affected.

See also the description copy! and copy.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

Examples

julia> x = [1., 0., 3., 0., 5.];

julia> y = zeros(7);

julia> copyto!(y, x);

julia> y
7-element Vector{Float64}:
 1.0
 0.0
 3.0
 0.0
 5.0
 0.0
 0.0

copyto!(dest, Rdest::CartesianIndices, src, Rsrc::CartesianIndices) -> dest

Copies the src block in the Rsrc range to the dest block in the Rdest range. The sizes of the two regions must match.

Examples

julia> A = zeros(5, 5);

julia> B = [1 2; 3 4];

julia> Ainds = CartesianIndices((2:3, 2:3));

julia> Binds = CartesianIndices(B);

julia> copyto!(A, Ainds, B, Binds)
5×5 Matrix{Float64}:
 0.0  0.0  0.0  0.0  0.0
 0.0  1.0  2.0  0.0  0.0
 0.0  3.0  4.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
pointer(array [, index])

Gets its own address of the array or string (if necessary, by the index of the specified location).

This function is unsafe. Make sure that Julia’s reference to the array exists for the entire time the pointer is used. The macro GC.@preserve ` should be used to protect the `array argument for garbage collection within a given block of code.

Usually the most preferred option is to call Ref(array[, index]), since this guarantees the validity of the result.

unsafe_wrap(Array, pointer::Ptr{T}, dims; own = false)

Encloses data in the Julia Array object at the address specified by the pointer', without creating a copy. The type of pointer elements `T defines the type of array elements. dims is either an integer (for a one-dimensional array) or a tuple of array dimensions. own additionally indicates whether the Julia environment should own the memory by calling free for the pointer when there are no more references to the array.

This function is marked as "unsafe" because it will fail if the pointer' is not a valid memory address for data of the requested length. As opposed to `unsafe load and unsafe store!, the programmer is also responsible for ensuring that access to the underlying data is not carried out through two arrays with different types of elements, similar to the strict rule for assigning aliases in C.

pointer_from_objref(x)

Gets the Julia object’s memory address in the form of Ptr'. The existence of the resulting `Ptr will not protect the object from garbage collection, so it must be ensured that the object is referenced throughout the entire time the Ptr is used.

This function cannot be called for immutable objects because they lack stable memory addresses.

See also the description unsafe_pointer_to_objref.

unsafe_pointer_to_objref(p::Ptr)

Converts the Ptr to an object reference. It is assumed that the pointer refers to a valid Julia object allocated on the heap. If this is not the case, undefined behavior begins to take effect, so this function is considered "unsafe" and should be used with caution.

See also the description pointer_from_objref.

disable_sigint(f::Function)

Disables the Ctrl-C handler during the execution of a function in the current task to invoke external code that may invoke Julia code that is not safe for interrupts. It is intended to be invoked using the syntax of the do block as follows:

disable_sigint() do # interrupt-unsafe code ... end

It is not intended for worker threads (Threads.threadid() != 1), because the InterruptException is delivered only to the main thread. External functions that do not invoke the Julia code or runtime automatically disable signal intelligence during their execution.

reenable_sigint(f::Function)

Re-enables the Ctrl-C handler during function execution. Temporarily cancels the effect of the action disable_sigint.

exit_on_sigint(on::Bool)

Sets the exit_on_sigint flag of the Julia runtime. If false', Ctrl-C (SIGINT) is fixed as `InterruptException in the 'try` block. This is the default behavior in REPL: any code is executed with the -e and -E' parameters, and the Julia script is executed with the '-i parameter.

If true, Ctrl-C does not cause an InterruptException'. To execute the code at such an event, it is required `atexit. This is the default behavior for executing the Julia script without the '-i` parameter.

Compatibility: Julia 1.5

The exit_on_sigint function requires a Julia version at least 1.5.

systemerror(sysfunc[, errno::Cint=Libc.errno()])
systemerror(sysfunc, iftrue::Bool)

Calls SystemError for errno' with a string with the description `sysfunc if iftrue has the value `true'.

windowserror(sysfunc[, code::UInt32=Libc.GetLastError()])
windowserror(sysfunc, iftrue::Bool)

Similarly 'systemerror`, but applies to Windows API functions that use GetLastError to return an error code instead of a task errno.

Ptr{T}

The memory address related to data of type `T'. However, there is no guarantee that the memory is actually valid or that it represents data of the specified type.

Ref{T}

An object that safely references data of type T'. This type is guaranteed to point to valid memory allocated in Julia of the correct type. The underlying data is protected from being freed by the garbage collector as long as there is a reference to `Ref.

In Julia, Ref objects are dereferenced (loaded or stored) using [].

Creating a Ref with an x value of type T is usually written as Ref(x). In addition, when creating internal pointers to containers (such as Array or Ptr), the function can be written as Ref(a, i) to create a reference to the i’th the `a element.

Ref{T}() creates a reference to a value of type T without initialization. For the bit type T, the value will be what is currently in the allocated memory. For a non-bit type T, the link will be undefined, and an attempt to dereference it will result in the error "UndefRefError: access to an undefined link".

To check if Ref is an undefined reference, use isassigned(ref::RefValue). For example, isassigned(Ref{T}()) has the value false if T is a non-bit type. If T is a bit type, isassigned(Ref{T}()) will always have the value true.

When passed as a ccall' argument (such as `Ptr or Ref), the Ref object will be converted into its own pointer to the data it refers to. For most, T or when converted to Ptr{Cvoid} the object will be a pointer to the object’s data. If 'T` is of type `isbits', this value can be easily changed, otherwise the change is strictly undefined behavior.

As a special case, setting T = Any will create a pointer to the link itself when converting to Ptr{Any} ('jl_value_t const* const*` if T is immutable, otherwise jl_value_t *const *). When converting to +Ptr{Cvoid}The + will still return a pointer to the data area, as for the other T.

An instance of C_NULL Ptr can be passed in the Ref argument to `ccall' to initialize it.

Use in broadcasting

Ref is sometimes used in translation so that the values referenced are treated as scalars.

Examples

julia> r = Ref(5) # Создание ссылки с начальным значением
Base.RefValue{Int64}(5)

julia> r[] # Получение значения из Ref
5

julia> r[] = 7 # Сохранение нового значения в Ref
7

julia> r # Ref теперь содержит значение 7
Base.RefValue{Int64}(7)

julia> isa.(Ref([1,2,3]), [Array, Dict, Int]) # Считает значения, на которые указывает ссылка, скалярными во время трансляции
3-element BitVector:
 1
 0
 0

julia> Ref{Function}()  # Неопределенная ссылка на небитовый тип, функция
Base.RefValue{Function}(#undef)

julia> try
           Ref{Function}()[] # Разыменование неопределенной ссылки приведет к ошибке
       catch e
           println(e)
       end
UndefRefError()

julia> Ref{Int64}()[]; # Ссылка на битовый тип относится к неопределенному значению, если оно не задано

julia> isassigned(Ref{Int64}()) # Ссылка на битовый тип всегда присваивается
true
isassigned(ref::RefValue) -> Bool

Checks whether the specified one is connected. Ref with a value. For Ref of a bit-type object, the result is always true. Returns false if the reference is not defined.

Examples

julia> ref = Ref{Function}()
Base.RefValue{Function}(#undef)

julia> isassigned(ref)
false

julia> ref[] = (foobar(x) = x)
foobar (generic function with 1 method)

julia> isassigned(ref)
true

julia> isassigned(Ref{Int}())
true
Cchar

Is equivalent to the native C type char.

Cuchar

Equivalent to the native C type unsigned char (UInt8).

Cshort

Equivalent to the native C type signed short (Int16).

Cstring

A C-style string consisting of Cchar of its own character type. 'Cstring` ends with a null character. For information about C-style strings consisting of extended characters of their own type, see the description Cwstring. For more information about how strings interact with C, see the manual.

Cushort

Equivalent to the native C type unsigned short (UInt16).

Cint

Equivalent to the native C type signed int (Int32).

Cuint

Equivalent to the native C type unsigned int (UInt32).

Clong

It is equivalent to the native C type signed long.

Culong

It is equivalent to the native C type unsigned long.

Clonglong

Equivalent to the native type C signed long long (Int64).

Culonglong

Equivalent to the native C type unsigned long long (UInt64).

Cintmax_t

Equivalent to the native C type intmax_t (Int64).

Cuintmax_t

Equivalent to the native C type uintmax_t (UInt64).

Csize_t

It is equivalent to the native C type size_t (UInt).

Cssize_t

It is equivalent to the native C type `ssize_t'.

Cptrdiff_t

It is equivalent to the native C type ptrdiff_t (Int).

Cwchar_t

Equivalent to C’s own type wchar_t' (`Int32).

Cwstring

A C-style string consisting of Cwchar_t is a custom type of extended characters. The 'Cwstring` ends with a null character. For information about C-style strings consisting of characters of their own type, see the description Cstring. For more information about how strings interact with C, see the manual.

Cfloat

Equivalent to the native C float type (Float32).

Cdouble

Equivalent to the native type C double (Float64).

LLVM Interface

llvmcall(fun_ir::String, returntype, Tuple{argtype1, ...}, argvalue1, ...)
llvmcall((mod_ir::String, entry_fn::String), returntype, Tuple{argtype1, ...}, argvalue1, ...)
llvmcall((mod_bc::Vector{UInt8}, entry_fn::String), returntype, Tuple{argtype1, ...}, argvalue1, ...)

Calls the LLVM code given in the first argument. There are several ways to specify this first argument.:

  • as a literal string representing the IR environment of the function level (similar to the LLVM define block), with arguments available as consecutive unnamed SSA variables (%0, %1, etc.);

  • in the form of a two-element tuple containing a string of the IR environment module and a string representing the name of the entry point function being called.;

  • in the form of a two-element tuple with a module represented as a Vector{UInt8} with a bit code.

Note that unlike ccall, the argument types must be specified as a tuple type, not a tuple of types. All types, as well as LLVM code, must be specified as literals, not variables or expressions (you may need to use @eval to create these literals).

Opaque pointers (written as ptr) are not allowed in LLVM code.

See https://github.com/JuliaLang/julia/blob/v1.11.3/test/llvmcall.jl [test/llvmcall.jl] with usage examples.