Movatterモバイル変換


[0]ホーム

URL:


GitHub

C Interface

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

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

Eachargvalue to@ccall is converted to the correspondingargtype, by automatic insertion of calls tounsafe_convert(argtype, cconvert(argtype, argvalue)). (See also the documentation forunsafe_convert andcconvert for further details.) In most cases, this simply results in a call toconvert(argtype, argvalue).

Examples

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

This calls the C standard library function:

size_t strlen(char *)

with a Julia variable nameds. See alsoccall.

Varargs are supported with the following convention:

@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:

# C signature of 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

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

source
ccallKeyword
ccall((function_name, library), returntype, (argtype1, ...), argvalue1, ...)ccall(function_name, returntype, (argtype1, ...), argvalue1, ...)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 afunction_name symbol or string, which is resolved in the current process. Alternatively,ccall may also be used to call a function pointerfunction_pointer, such as one returned bydlsym.

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

Eachargvalue to theccall will be converted to the correspondingargtype, by automatic insertion of calls tounsafe_convert(argtype, cconvert(argtype, argvalue)). (See also the documentation forunsafe_convert andcconvert for further details.) In most cases, this simply results in a call toconvert(argtype, argvalue).

source
Core.Intrinsics.cglobalFunction
cglobal((symbol, library) [, type=Cvoid])

Obtain a pointer to a global variable in a C-exported shared library, specified exactly as inccall. Returns aPtr{Type}, defaulting toPtr{Cvoid} if noType argument is supplied. The values can be read or written byunsafe_load orunsafe_store!, respectively.

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

Generate a C-callable function pointer from the Julia functioncallable for the given type signature. To pass the return value to accall, use the argument typePtr{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 variablecallable (this is not supported on all architectures).

Seemanual section on ccall and cfunction usage.

Examples

julia> function foo(x::Int, y::Int)           return x + y       endjulia> @cfunction(foo, Int, (Int, Int))Ptr{Cvoid} @0x000000001b82fcd0
source
Base.CFunctionType
CFunction struct

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

See@cfunction.

source
Base.unsafe_convertFunction
unsafe_convert(T, x)

Convertx to a C argument of typeT where the inputx must be the return value ofcconvert(T, ...).

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

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

Theunsafe prefix on this function indicates that using the result of this function after thex 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 alsocconvert

source
Base.cconvertFunction
cconvert(T,x)

Convertx to a value to be passed to C code as typeT, typically by callingconvert(T, x).

In cases wherex cannot be safely converted toT, unlikeconvert,cconvert may return an object of a type different fromT, which however is suitable forunsafe_convert to handle. The result of this function should be kept valid (for the GC) until the result ofunsafe_convert is not needed anymore. This can be used to allocate memory that will be accessed by theccall. If multiple objects need to be allocated, a tuple of the objects can be used as return value.

Neitherconvert norcconvert should take a Julia object and turn it into aPtr.

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

Load a value of typeT from the address of theith element (1-indexed) starting atp. This is equivalent to the C expressionp[i-1]. Optionally, an atomic memory ordering can be provided.

Theunsafe prefix on this function indicates that no validation is performed on the pointerp 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

Theorder argument is available as of Julia 1.10.

See also:atomic

source
Base.unsafe_store!Function
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)

Store a value of typeT to the address of theith element (1-indexed) starting atp. This is equivalent to the C expressionp[i-1] = x. Optionally, an atomic memory ordering can be provided.

Theunsafe prefix on this function indicates that no validation is performed on the pointerp 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

Theorder argument is available as of Julia 1.10.

See also:atomic

source
Base.unsafe_modify!Function
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 functionop. 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:

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

Theunsafe prefix on this function indicates that no validation is performed on the pointerp 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
unsafe_replace!(p::Ptr{T}, expected, desired,               [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:

y = unsafe_load(p, fail_order)ok = y === expectedif ok    unsafe_store!(p, desired, success_order)endreturn (; old = y, success = ok)

Theunsafe prefix on this function indicates that no validation is performed on the pointerp 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
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:

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

Theunsafe prefix on this function indicates that no validation is performed on the pointerp 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
unsafe_copyto!(dest::Ptr{T}, src::Ptr{T}, N)

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

Theunsafe prefix on this function indicates that no validation is performed on the pointersdest andsrc 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
unsafe_copyto!(dest::Array, do, src::Array, so, N)

CopyN elements from a source array to a destination, starting at the linear indexso in the source anddo in the destination (1-indexed).

Theunsafe 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.

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

Efficiently copy elements of matrixM toB conditioned on the character parametertM as follows:

tMDestinationSource
'N'B[ir_dest, jr_dest]M[ir_src, jr_src]
'T'B[ir_dest, jr_dest]transpose(M)[ir_src, jr_src]
'C'B[ir_dest, jr_dest]adjoint(M)[ir_src, jr_src]

The elementsB[ir_dest, jr_dest] are overwritten. Furthermore, the index range parameters must satisfylength(ir_dest) == length(ir_src) andlength(jr_dest) == length(jr_src).

See alsocopy_transpose! andcopy_adjoint!.

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

Copies aUniformScaling 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.

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

CopyN elements from collectionsrc starting at the linear indexso, to arraydest starting at the indexdo. Returndest.

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

Copy all elements from collectionsrc to arraydest, whose length must be greater than or equal to the lengthn ofsrc. The firstn elements ofdest are overwritten, the other elements are left untouched.

See alsocopy!,copy.

Warning

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

Examples

julia> x = [1., 0., 3., 0., 5.];julia> y = zeros(7);julia> copyto!(y, x);julia> y7-element Vector{Float64}: 1.0 0.0 3.0 0.0 5.0 0.0 0.0
source
copyto!(dest, Rdest::CartesianIndices, src, Rsrc::CartesianIndices) -> dest

Copy the block ofsrc in the range ofRsrc to the block ofdest in the range ofRdest. 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
source
Base.pointerFunction
pointer(array [, index])

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

This function is "unsafe". Be careful to ensure that a Julia reference toarray exists as long as this pointer will be used. TheGC.@preserve macro should be used to protect thearray argument from garbage collection within a given block of code.

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

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

Wrap a JuliaArray object around the data at the address given bypointer, without making a copy. The pointer element typeT 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, callingfree on the pointer when the array is no longer referenced.

This function is labeled "unsafe" because it will crash ifpointer is not a valid memory address to data of the requested length. Unlikeunsafe_load andunsafe_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_objrefFunction
pointer_from_objref(x)

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

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

See alsounsafe_pointer_to_objref.

source
Base.unsafe_pointer_to_objrefFunction
unsafe_pointer_to_objref(p::Ptr)

Convert aPtr 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 alsopointer_from_objref.

source
Base.disable_sigintFunction
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 usingdo block syntax as follows:

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

This is not needed on worker threads (Threads.threadid() != 1) since theInterruptException 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_sigintFunction
reenable_sigint(f::Function)

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

source
Base.exit_on_sigintFunction
exit_on_sigint(on::Bool)

Setexit_on_sigint flag of the julia runtime. Iffalse, Ctrl-C (SIGINT) is capturable asInterruptException intry block. This is the default behavior in REPL, any code run via-e and-E and in Julia script run with-i option.

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

Julia 1.5

Functionexit_on_sigint requires at least Julia 1.5.

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

Raises aSystemError forerrno with the descriptive stringsysfunc ififtrue istrue

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

Likesystemerror, but for Windows API functions that useGetLastError to return an error code instead of settingerrno.

source
Core.PtrType
Ptr{T}

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

source
Core.RefType
Ref{T}

An object that safely references data of typeT. 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 theRef itself is referenced.

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

Creation of aRef to a valuex of typeT is usually writtenRef(x). Additionally, for creating interior pointers to containers (such as Array or Ptr), it can be writtenRef(a, i) for creating a reference to thei-th element ofa.

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

To check if aRef is an undefined reference, useisassigned(ref::RefValue). For example,isassigned(Ref{T}()) isfalse ifT is not a bitstype. IfT is a bitstype,isassigned(Ref{T}()) will always be true.

When passed as accall argument (either as aPtr orRef type), aRef object will be converted to a native pointer to the data it references. For mostT, or when converted to aPtr{Cvoid}, this is a pointer to the object data. WhenT is anisbits type, this value may be safely mutated, otherwise mutation is strictly undefined behavior.

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

AC_NULL instance ofPtr can be passed to accallRef argument to initialize it.

Use in broadcasting

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

Examples

julia> r = Ref(5) # Create a Ref with an initial valueBase.RefValue{Int64}(5)julia> r[] # Getting a value from a Ref5julia> r[] = 7 # Storing a new value in a Ref7julia> r # The Ref now contains 7Base.RefValue{Int64}(7)julia> isa.(Ref([1,2,3]), [Array, Dict, Int]) # Treat reference values as scalar during broadcasting3-element BitVector: 1 0 0julia> Ref{Function}()  # Undefined reference to a non-bitstype, FunctionBase.RefValue{Function}(#undef)julia> try           Ref{Function}()[] # Dereferencing an undefined reference will result in an error       catch e           println(e)       endUndefRefError()julia> Ref{Int64}()[]; # A reference to a bitstype refers to an undetermined value if not givenjulia> isassigned(Ref{Int64}()) # A reference to a bitstype is always assignedtrue
source
Base.isassignedMethod
isassigned(ref::RefValue) -> Bool

Test whether the givenRef is associated with a value. This is always true for aRef of a bitstype object. Returnfalse if the reference is undefined.

Examples

julia> ref = Ref{Function}()Base.RefValue{Function}(#undef)julia> isassigned(ref)falsejulia> ref[] = (foobar(x) = x)foobar (generic function with 1 method)julia> isassigned(ref)truejulia> isassigned(Ref{Int}())true
source
Base.CcharType
Cchar

Equivalent to the nativechar c-type.

source
Base.CucharType
Cuchar

Equivalent to the nativeunsigned char c-type (UInt8).

source
Base.CshortType
Cshort

Equivalent to the nativesigned short c-type (Int16).

source
Base.CstringType
Cstring

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

source
Base.CushortType
Cushort

Equivalent to the nativeunsigned short c-type (UInt16).

source
Base.CintType
Cint

Equivalent to the nativesigned int c-type (Int32).

source
Base.CuintType
Cuint

Equivalent to the nativeunsigned int c-type (UInt32).

source
Base.ClongType
Clong

Equivalent to the nativesigned long c-type.

source
Base.CulongType
Culong

Equivalent to the nativeunsigned long c-type.

source
Base.ClonglongType
Clonglong

Equivalent to the nativesigned long long c-type (Int64).

source
Base.CulonglongType
Culonglong

Equivalent to the nativeunsigned long long c-type (UInt64).

source
Base.Cintmax_tType
Cintmax_t

Equivalent to the nativeintmax_t c-type (Int64).

source
Base.Cuintmax_tType
Cuintmax_t

Equivalent to the nativeuintmax_t c-type (UInt64).

source
Base.Csize_tType
Csize_t

Equivalent to the nativesize_t c-type (UInt).

source
Base.Cssize_tType
Cssize_t

Equivalent to the nativessize_t c-type.

source
Base.Cptrdiff_tType
Cptrdiff_t

Equivalent to the nativeptrdiff_t c-type (Int).

source
Base.Cwchar_tType
Cwchar_t

Equivalent to the nativewchar_t c-type (Int32).

source
Base.CwstringType
Cwstring

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

source
Base.CfloatType
Cfloat

Equivalent to the nativefloat c-type (Float32).

source
Base.CdoubleType
Cdouble

Equivalent to the nativedouble c-type (Float64).

source

LLVM Interface

Core.Intrinsics.llvmcallFunction
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, ...)

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 LLVMdefine 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 anVector{UInt8} with bitcode.

Note that contrary toccall, 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).

Opaque pointers (written asptr) are not allowed in the LLVM code.

Seetest/llvmcall.jl for usage examples.

source

Settings


This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.


[8]ページ先頭

©2009-2025 Movatter.jp