C Interface

Base.@ccall — Macro

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

Call a function in a C-exported shared library, specified by library.function_name, where library is a string constant or literal. The library may be omitted, in which case the function_name is resolved in the current process. Alternatively, @ccall may also be used to call a function pointer $function_pointer, such as one returned by dlsym.

Each argvalue to @ccall is converted to the corresponding argtype, by automatic insertion of calls to unsafe_convert(argtype, cconvert(argtype, argvalue)). (See also the documentation for unsafe_convert and cconvert for further details.) In most cases, this simply results in a call to convert(argtype, argvalue).

Examples

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

This calls the C standard library function:

  1. size_t strlen(char *)

with a Julia variable named s. See also ccall.

Varargs are supported with the following convention:

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

The semicolon is used to separate required arguments (of which there must be at least one) from variadic arguments.

Example using an external library:

  1. # C signature of g_uri_escape_string:
  2. # char *g_uri_escape_string(const char *unescaped, const char *reserved_chars_allowed, gboolean allow_utf8);
  3. const glib = "libglib-2.0"
  4. @ccall glib.g_uri_escape_string(my_uri::Cstring, ":/"::Cstring, true::Cint)::Cstring

The string literal could also be used directly before the function name, if desired "libglib-2.0".g_uri_escape_string(...

source

ccall — Keyword

  1. ccall((function_name, library), returntype, (argtype1, ...), argvalue1, ...)
  2. ccall(function_name, returntype, (argtype1, ...), argvalue1, ...)
  3. ccall(function_pointer, returntype, (argtype1, ...), argvalue1, ...)

Call a function in a C-exported shared library, specified by the tuple (function_name, library), where each component is either a string or symbol. Instead of specifying a library, one can also use a function_name symbol or string, which is resolved in the current process. Alternatively, ccall may also be used to call a function pointer function_pointer, such as one returned by dlsym.

Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression.

Each argvalue to the ccall will be converted to the corresponding argtype, by automatic insertion of calls to unsafe_convert(argtype, cconvert(argtype, argvalue)). (See also the documentation for unsafe_convert and cconvert for further details.) In most cases, this simply results in a call to convert(argtype, argvalue).

source

Core.Intrinsics.cglobal — Function

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

Obtain a pointer to a global variable in a C-exported shared library, specified exactly as in ccall. Returns a Ptr{Type}, defaulting to Ptr{Cvoid} if no Type argument is supplied. The values can be read or written by unsafe_load or unsafe_store!, respectively.

source

Base.@cfunction — Macro

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

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

Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression (although it can include a splat expression). And that these arguments will be evaluated in global scope during compile-time (not deferred until runtime). Adding a ‘$’ in front of the function argument changes this to instead create a runtime closure over the local variable callable (this is not supported on all architectures).

See manual section on ccall and cfunction usage.

Examples

  1. julia> function foo(x::Int, y::Int)
  2. return x + y
  3. end
  4. julia> @cfunction(foo, Int, (Int, Int))
  5. Ptr{Cvoid} @0x000000001b82fcd0

source

Base.CFunction — Type

  1. CFunction struct

Garbage-collection handle for the return value from @cfunction when the first argument is annotated with ‘$’. Like all cfunction handles, it should be passed to ccall as a Ptr{Cvoid}, and will be converted automatically at the call site to the appropriate type.

See @cfunction.

source

Base.unsafe_convert — Function

  1. unsafe_convert(T, x)

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

In cases where convert would need to take a Julia object and turn it into a Ptr, this function should be used to define and perform that conversion.

Be careful to ensure that a Julia reference to x exists as long as the result of this function will be used. Accordingly, the argument x to this function should never be an expression, only a variable name or field reference. For example, x=a.b.c is acceptable, but x=[a,b,c] is not.

The unsafe prefix on this function indicates that using the result of this function after the x argument to this function is no longer accessible to the program may cause undefined behavior, including program corruption or segfaults, at any later time.

See also cconvert

source

Base.cconvert — Function

  1. cconvert(T,x)

Convert x to a value to be passed to C code as type T, typically by calling convert(T, x).

In cases where x cannot be safely converted to T, unlike convert, cconvert may return an object of a type different from T, which however is suitable for unsafe_convert to handle. The result of this function should be kept valid (for the GC) until the result of unsafe_convert is not needed anymore. This can be used to allocate memory that will be accessed by the ccall. If multiple objects need to be allocated, a tuple of the objects can be used as return value.

Neither convert nor cconvert should take a Julia object and turn it into a Ptr.

source

Base.unsafe_load — Function

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

Load a value of type T from the address of the ith element (1-indexed) starting at p. This is equivalent to the C expression p[i-1]. Optionally, an atomic memory ordering can be provided.

The unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Like C, the programmer is responsible for ensuring that referenced memory is not freed or garbage collected while invoking this function. Incorrect usage may segfault your program or return garbage answers. Unlike C, dereferencing memory region allocated as different type may be valid provided that the types are compatible.

Julia 1.10

The order argument is available as of Julia 1.10.

See also: atomic

source

Base.unsafe_store! — Function

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

Store a value of type T to the address of the ith element (1-indexed) starting at p. This is equivalent to the C expression p[i-1] = x. Optionally, an atomic memory ordering can be provided.

The unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Like C, the programmer is responsible for ensuring that referenced memory is not freed or garbage collected while invoking this function. Incorrect usage may segfault your program. Unlike C, storing memory region allocated as different type may be valid provided that that the types are compatible.

Julia 1.10

The order argument is available as of Julia 1.10.

See also: atomic

source

Base.unsafe_modify! — Function

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

These atomically perform the operations to get and set a memory address after applying the function op. If supported by the hardware (for example, atomic increment), this may be optimized to the appropriate hardware instruction, otherwise its execution will be similar to:

  1. y = unsafe_load(p)
  2. z = op(y, x)
  3. unsafe_store!(p, z)
  4. return y => z

The unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Like C, the programmer is responsible for ensuring that referenced memory is not freed or garbage collected while invoking this function. Incorrect usage may segfault your program.

Julia 1.10

This function requires at least Julia 1.10.

See also: modifyproperty!, atomic

source

Base.unsafe_replace! — Function

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

These atomically perform the operations to get and conditionally set a memory address to a given value. If supported by the hardware, this may be optimized to the appropriate hardware instruction, otherwise its execution will be similar to:

  1. y = unsafe_load(p, fail_order)
  2. ok = y === expected
  3. if ok
  4. unsafe_store!(p, desired, success_order)
  5. end
  6. return (; old = y, success = ok)

The unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Like C, the programmer is responsible for ensuring that referenced memory is not freed or garbage collected while invoking this function. Incorrect usage may segfault your program.

Julia 1.10

This function requires at least Julia 1.10.

See also: replaceproperty!, atomic

source

Base.unsafe_swap! — Function

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

These atomically perform the operations to simultaneously get and set a memory address. If supported by the hardware, this may be optimized to the appropriate hardware instruction, otherwise its execution will be similar to:

  1. y = unsafe_load(p)
  2. unsafe_store!(p, x)
  3. return y

The unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Like C, the programmer is responsible for ensuring that referenced memory is not freed or garbage collected while invoking this function. Incorrect usage may segfault your program.

Julia 1.10

This function requires at least Julia 1.10.

See also: swapproperty!, atomic

source

Base.unsafe_copyto! — Method

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

Copy N elements from a source pointer to a destination, with no checking. The size of an element is determined by the type of the pointers.

The unsafe prefix on this function indicates that no validation is performed on the pointers dest and src to ensure that they are valid. Incorrect usage may corrupt or segfault your program, in the same manner as C.

source

Base.unsafe_copyto! — Method

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

Copy N elements from a source array to a destination, starting at the linear index so in the source and do in the destination (1-indexed).

The unsafe prefix on this function indicates that no validation is performed to ensure that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in the same manner as C.

Warning

Behavior can be unexpected when any mutated argument shares memory with any other argument.

source

Base.copyto! — Function

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

Copies a UniformScaling onto a matrix.

Julia 1.1

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

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

Copy N elements from collection src starting at the linear index so, to array dest starting at the index do. Return dest.

source

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

Copy all elements from collection src to array dest, whose length must be greater than or equal to the length n of src. The first n elements of dest are overwritten, the other elements are left untouched.

See also copy!, copy.

Examples

  1. julia> x = [1., 0., 3., 0., 5.];
  2. julia> y = zeros(7);
  3. julia> copyto!(y, x);
  4. julia> y
  5. 7-element Vector{Float64}:
  6. 1.0
  7. 0.0
  8. 3.0
  9. 0.0
  10. 5.0
  11. 0.0
  12. 0.0

source

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

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

Examples

  1. julia> A = zeros(5, 5);
  2. julia> B = [1 2; 3 4];
  3. julia> Ainds = CartesianIndices((2:3, 2:3));
  4. julia> Binds = CartesianIndices(B);
  5. julia> copyto!(A, Ainds, B, Binds)
  6. 5×5 Matrix{Float64}:
  7. 0.0 0.0 0.0 0.0 0.0
  8. 0.0 1.0 2.0 0.0 0.0
  9. 0.0 3.0 4.0 0.0 0.0
  10. 0.0 0.0 0.0 0.0 0.0
  11. 0.0 0.0 0.0 0.0 0.0

source

Base.pointer — Function

  1. pointer(array [, index])

Get the native address of an array or string, optionally at a given location index.

This function is “unsafe”. Be careful to ensure that a Julia reference to array exists as long as this pointer will be used. The GC.@preserve macro should be used to protect the array argument from garbage collection within a given block of code.

Calling Ref(array[, index]) is generally preferable to this function as it guarantees validity.

source

Base.unsafe_wrap — Method

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

Wrap a Julia Array object around the data at the address given by pointer, without making a copy. The pointer element type T determines the array element type. dims is either an integer (for a 1d array) or a tuple of the array dimensions. own optionally specifies whether Julia should take ownership of the memory, calling free on the pointer when the array is no longer referenced.

This function is labeled “unsafe” because it will crash if pointer is not a valid memory address to data of the requested length. Unlike unsafe_load and unsafe_store!, the programmer is responsible also for ensuring that the underlying data is not accessed through two arrays of different element type, similar to the strict aliasing rule in C.

source

Base.pointer_from_objref — Function

  1. pointer_from_objref(x)

Get the memory address of a Julia object as a Ptr. The existence of the resulting Ptr will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr will be used.

This function may not be called on immutable objects, since they do not have stable memory addresses.

See also unsafe_pointer_to_objref.

source

Base.unsafe_pointer_to_objref — Function

  1. unsafe_pointer_to_objref(p::Ptr)

Convert a Ptr to an object reference. Assumes the pointer refers to a valid heap-allocated Julia object. If this is not the case, undefined behavior results, hence this function is considered “unsafe” and should be used with care.

See also pointer_from_objref.

source

Base.disable_sigint — Function

  1. disable_sigint(f::Function)

Disable Ctrl-C handler during execution of a function on the current task, for calling external code that may call julia code that is not interrupt safe. Intended to be called using do block syntax as follows:

  1. disable_sigint() do
  2. # interrupt-unsafe code
  3. ...
  4. end

This is not needed on worker threads (Threads.threadid() != 1) since the InterruptException will only be delivered to the master thread. External functions that do not call julia code or julia runtime automatically disable sigint during their execution.

source

Base.reenable_sigint — Function

  1. reenable_sigint(f::Function)

Re-enable Ctrl-C handler during execution of a function. Temporarily reverses the effect of disable_sigint.

source

Base.exit_on_sigint — Function

  1. exit_on_sigint(on::Bool)

Set exit_on_sigint flag of the julia runtime. If false, Ctrl-C (SIGINT) is capturable as InterruptException in try block. This is the default behavior in REPL, any code run via -e and -E and in Julia script run with -i option.

If true, InterruptException is not thrown by Ctrl-C. Running code upon such event requires atexit. This is the default behavior in Julia script run without -i option.

Julia 1.5

Function exit_on_sigint requires at least Julia 1.5.

source

Base.systemerror — Function

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

Raises a SystemError for errno with the descriptive string sysfunc if iftrue is true

source

Base.windowserror — Function

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

Like systemerror, but for Windows API functions that use GetLastError to return an error code instead of setting errno.

source

Core.Ptr — Type

  1. Ptr{T}

A memory address referring to data of type T. However, there is no guarantee that the memory is actually valid, or that it actually represents data of the specified type.

source

Core.Ref — Type

  1. Ref{T}

An object that safely references data of type T. This type is guaranteed to point to valid, Julia-allocated memory of the correct type. The underlying data is protected from freeing by the garbage collector as long as the Ref itself is referenced.

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

Creation of a Ref to a value x of type T is usually written Ref(x). Additionally, for creating interior pointers to containers (such as Array or Ptr), it can be written Ref(a, i) for creating a reference to the i-th element of a.

Ref{T}() creates a reference to a value of type T without initialization. For a bitstype T, the value will be whatever currently resides in the memory allocated. For a non-bitstype T, the reference will be undefined and attempting to dereference it will result in an error, “UndefRefError: access to undefined reference”.

To check if a Ref is an undefined reference, use isassigned(ref::RefValue). For example, isassigned(Ref{T}()) is false if T is not a bitstype. If T is a bitstype, isassigned(Ref{T}()) will always be true.

When passed as a ccall argument (either as a Ptr or Ref type), a Ref object will be converted to a native pointer to the data it references. For most T, or when converted to a Ptr{Cvoid}, this is a pointer to the object data. When T is an isbits type, this value may be safely mutated, otherwise mutation is strictly undefined behavior.

As a special case, setting T = Any will instead cause the creation of a pointer to the reference itself when converted to a Ptr{Any} (a jl_value_t const* const* if T is immutable, else a jl_value_t *const *). When converted to a Ptr{Cvoid}, it will still return a pointer to the data region as for any other T.

A C_NULL instance of Ptr can be passed to a ccall Ref argument to initialize it.

Use in broadcasting

Ref is sometimes used in broadcasting in order to treat the referenced values as a scalar.

Examples

  1. julia> Ref(5)
  2. Base.RefValue{Int64}(5)
  3. julia> isa.(Ref([1,2,3]), [Array, Dict, Int]) # Treat reference values as scalar during broadcasting
  4. 3-element BitVector:
  5. 1
  6. 0
  7. 0
  8. julia> Ref{Function}() # Undefined reference to a non-bitstype, Function
  9. Base.RefValue{Function}(#undef)
  10. julia> try
  11. Ref{Function}()[] # Dereferencing an undefined reference will result in an error
  12. catch e
  13. println(e)
  14. end
  15. UndefRefError()
  16. julia> Ref{Int64}()[]; # A reference to a bitstype refers to an undetermined value if not given
  17. julia> isassigned(Ref{Int64}()) # A reference to a bitstype is always assigned
  18. true
  19. julia> Ref{Int64}(0)[] == 0 # Explicitly give a value for a bitstype reference
  20. true

source

Base.isassigned — Method

  1. isassigned(ref::RefValue) -> Bool

Test whether the given Ref is associated with a value. This is always true for a Ref of a bitstype object. Return false if the reference is undefined.

Examples

  1. julia> ref = Ref{Function}()
  2. Base.RefValue{Function}(#undef)
  3. julia> isassigned(ref)
  4. false
  5. julia> ref[] = (foobar(x) = x)
  6. foobar (generic function with 1 method)
  7. julia> isassigned(ref)
  8. true
  9. julia> isassigned(Ref{Int}())
  10. true

source

Base.Cchar — Type

  1. Cchar

Equivalent to the native char c-type.

source

Base.Cuchar — Type

  1. Cuchar

Equivalent to the native unsigned char c-type (UInt8).

source

Base.Cshort — Type

  1. Cshort

Equivalent to the native signed short c-type (Int16).

source

Base.Cstring — Type

  1. Cstring

A C-style string composed of the native character type Cchars. Cstrings are NUL-terminated. For C-style strings composed of the native wide character type, see Cwstring. For more information about string interoperability with C, see the manual.

source

Base.Cushort — Type

  1. Cushort

Equivalent to the native unsigned short c-type (UInt16).

source

Base.Cint — Type

  1. Cint

Equivalent to the native signed int c-type (Int32).

source

Base.Cuint — Type

  1. Cuint

Equivalent to the native unsigned int c-type (UInt32).

source

Base.Clong — Type

  1. Clong

Equivalent to the native signed long c-type.

source

Base.Culong — Type

  1. Culong

Equivalent to the native unsigned long c-type.

source

Base.Clonglong — Type

  1. Clonglong

Equivalent to the native signed long long c-type (Int64).

source

Base.Culonglong — Type

  1. Culonglong

Equivalent to the native unsigned long long c-type (UInt64).

source

Base.Cintmax_t — Type

  1. Cintmax_t

Equivalent to the native intmax_t c-type (Int64).

source

Base.Cuintmax_t — Type

  1. Cuintmax_t

Equivalent to the native uintmax_t c-type (UInt64).

source

Base.Csize_t — Type

  1. Csize_t

Equivalent to the native size_t c-type (UInt).

source

Base.Cssize_t — Type

  1. Cssize_t

Equivalent to the native ssize_t c-type.

source

Base.Cptrdiff_t — Type

  1. Cptrdiff_t

Equivalent to the native ptrdiff_t c-type (Int).

source

Base.Cwchar_t — Type

  1. Cwchar_t

Equivalent to the native wchar_t c-type (Int32).

source

Base.Cwstring — Type

  1. Cwstring

A C-style string composed of the native wide character type Cwchar_ts. Cwstrings are NUL-terminated. For C-style strings composed of the native character type, see Cstring. For more information about string interoperability with C, see the manual.

source

Base.Cfloat — Type

  1. Cfloat

Equivalent to the native float c-type (Float32).

source

Base.Cdouble — Type

  1. Cdouble

Equivalent to the native double c-type (Float64).

source

LLVM Interface

Core.Intrinsics.llvmcall — Function

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

Call the LLVM code provided in the first argument. There are several ways to specify this first argument:

  • as a literal string, representing function-level IR (similar to an LLVM define block), with arguments are available as consecutive unnamed SSA variables (%0, %1, etc.);
  • as a 2-element tuple, containing a string of module IR and a string representing the name of the entry-point function to call;
  • as a 2-element tuple, but with the module provided as an Vector{UInt8} with bitcode.

Note that contrary to ccall, the argument types must be specified as a tuple type, and not a tuple of types. All types, as well as the LLVM code, should be specified as literals, and not as variables or expressions (it may be necessary to use @eval to generate these literals).

See test/llvmcall.jl for usage examples.

source