Learn how to call imported functions that are declared in a C header.
Swift imports any function declared in a C header as a Swift global function.
For example, consider the following C function declarations:
Here’s how Swift imports them:
Use a CVaListPointer to Call Variadic Functions
In Swift, you can call C variadic functions, such as vasprintf(_:_:_:), using the Swift
with functions. The
with function takes an array of
CVar values and provides a
CVa value within the body of a closure parameter, whereas the
get function returns this value directly. With either function, you pass the resulting
CVa value as the
va argument of the C variadic function.
For example, here’s how to call the
vasprintf(_: function in Swift:
Swift only imports C variadic functions that use a
va for their arguments. C functions that use the
... syntax for variadic arguments are not imported, and therefore can’t be called using
Call Functions with Pointer Parameters
Whenever possible, Swift avoids giving you direct access to pointers. When importing C function parameters, however, Swift maps pointer parameters to standard library pointer types. The following tables use
Type as a placeholder type name to indicate syntax for the mappings.
For return types, variables, and arguments, the following mappings apply:
For class types, the following mappings apply:
For pointers to untyped, raw memory, the following mappings apply:
C function pointers are imported into Swift as closures with the C function pointer calling convention, denoted by the
@convention(c) attribute. For example, a function pointer that has the type
int (*)(void) in C is imported into Swift as
@convention(c) () -> Int32.
If the type of the value pointed to by a C pointer cannot be represented by Swift, as is the case with an incomplete struct type, the pointer is imported as an