You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: doc/manual/calling-c-and-fortran-code.rst
+62-53Lines changed: 62 additions & 53 deletions
Original file line number
Diff line number
Diff line change
@@ -1,5 +1,7 @@
1
1
.. _man-calling-c-and-fortran-code:
2
2
3
+
.. currentmodule:: Base
4
+
3
5
****************************
4
6
Calling C and Fortran Code
5
7
****************************
@@ -11,7 +13,7 @@ and efficient to call C and Fortran functions. Julia has a "no
11
13
boilerplate" philosophy: functions can be called directly from Julia
12
14
without any "glue" code, code generation, or compilation — even from the
13
15
interactive prompt. This is accomplished just by making an appropriate call
14
-
with ``ccall`` syntax, which looks like an ordinary function call.
16
+
with :func:`ccall` syntax, which looks like an ordinary function call.
15
17
16
18
The code to be called must be available as a shared library. Most C and
17
19
Fortran libraries ship compiled as shared libraries already, but if you
@@ -38,10 +40,10 @@ the current process. This form can be used to call C library functions,
38
40
functions in the Julia runtime, or functions in an application linked to
39
41
Julia.
40
42
41
-
Finally, you can use ``ccall`` to actually generate a call to the
42
-
library function. Arguments to ``ccall`` are as follows:
43
+
Finally, you can use :func:`ccall` to actually generate a call to the
44
+
library function. Arguments to :func:`ccall` are as follows:
43
45
44
-
1. (:function, "library") pair (must be a constant, but see below).
46
+
1. ``(:function, "library")`` pair (must be a constant, but see below).
45
47
2. Return type, which may be any bits type, including ``Int32``,
46
48
``Int64``, ``Float64``, or ``Ptr{T}`` for any type parameter ``T``,
47
49
indicating a pointer to values of type ``T``, or ``Ptr{Void}`` for
@@ -86,7 +88,7 @@ rather than ``(Ptr{Uint8})``. This is because ``(Ptr{Uint8})`` is just
86
88
(Ptr{Uint8},)
87
89
88
90
In practice, especially when providing reusable functionality, one
89
-
generally wraps ``ccall`` uses in Julia functions that set up arguments
91
+
generally wraps :func:`ccall` uses in Julia functions that set up arguments
90
92
and then check for errors in whatever manner the C or Fortran function
91
93
indicates them, propagating to the Julia caller as exceptions. This is
92
94
especially important since C and Fortran APIs are notoriously
@@ -164,9 +166,9 @@ a real address operator, it may be used with any syntax, such as
164
166
``&0`` or ``&f(x)``.
165
167
166
168
Note that no C header files are used anywhere in the process. Currently,
167
-
it is not possible to pass structs and other non-primitive types from
169
+
it is not possible to pass ``struct``\ s and other non-primitive types from
168
170
Julia to C libraries. However, C functions that generate and use opaque
169
-
struct types by passing pointers to them can return such values
171
+
``struct`` types by passing pointers to them can return such values
170
172
to Julia as ``Ptr{Void}``, which can then be passed to other C functions
171
173
as ``Ptr{Void}``. Memory allocation and deallocation of such objects
172
174
must be handled by calls to the appropriate cleanup routines in the
@@ -175,7 +177,7 @@ libraries being used, just like in any C program.
175
177
Mapping C Types to Julia
176
178
------------------------
177
179
178
-
Julia automatically inserts calls to the ``convert`` function to convert
180
+
Julia automatically inserts calls to the :func:`convert` function to convert
179
181
each argument to the specified type. For example, the following call::
180
182
181
183
ccall( (:foo, "libfoo"), Void, (Int32, Float64),
@@ -198,7 +200,7 @@ array matches ``T``, and the address of the first element is passed.
198
200
This is done in order to avoid copying arrays unnecessarily.
199
201
200
202
Therefore, if an ``Array`` contains data in the wrong format, it will
201
-
have to be explicitly converted using a call such as ``int32(a)``.
203
+
have to be explicitly converted using a call such as :func:`int32(A) <int32>`.
202
204
203
205
To pass an array ``A`` as a pointer of a different type *without*
204
206
converting the data beforehand (for example, to pass a ``Float64`` array
@@ -212,7 +214,9 @@ Type correspondences
212
214
213
215
On all systems we currently support, basic C/C++ value types may be
214
216
translated to Julia types as follows. Every C type also has a corresponding
215
-
Julia type with the same name, prefixed by C. This can help for writing portable code (and remembering that an int in C is not the same as an Int in Julia).
217
+
Julia type with the same name, prefixed by C. This can help for writing
218
+
portable code (and remembering that an ``int`` in C is not the same as an
219
+
``Int`` in Julia).
216
220
217
221
**System-independent:**
218
222
@@ -300,11 +304,11 @@ can be called via the following Julia code::
300
304
301
305
For ``wchar_t*`` arguments, the Julia type should be ``Ptr{Wchar_t}``,
302
306
and data can be converted to/from ordinary Julia strings by the
303
-
``wstring(s)`` function (equivalent to either ``utf16(s)`` or ``utf32(s)``
304
-
depending upon the width of ``Cwchar_t``. Note also that ASCII, UTF-8,
305
-
UTF-16, and UTF-32 string data in Julia is internally NUL-terminated, so
306
-
it can be passed to C functions expecting NUL-terminated data without making
307
-
a copy.
307
+
:func:`wstring(s) <wstring>` function (equivalent to either :func:`utf16(s)
308
+
<utf16>` or :func:`utf32(s) <utf32>` depending upon the width of ``Cwchar_t``.
309
+
Note also that ASCII, UTF-8, UTF-16, and UTF-32 string data in Julia is
310
+
internally NUL-terminated, so it can be passed to C functions expecting
311
+
NUL-terminated data without making a copy.
308
312
309
313
Accessing Data through a Pointer
310
314
--------------------------------
@@ -313,9 +317,10 @@ to terminate abruptly or corrupt arbitrary process memory due to a bad pointer
313
317
or type declaration.
314
318
315
319
Given a ``Ptr{T}``, the contents of type ``T`` can generally be copied from
316
-
the referenced memory into a Julia object using ``unsafe_load(ptr, [index])``. The
317
-
index argument is optional (default is 1), and performs 1-based indexing. This
318
-
function is intentionally similar to the behavior of ``getindex()`` and ``setindex!()``
320
+
the referenced memory into a Julia object using :func:`unsafe_load(ptr,
321
+
[index]) <unsafe_load>`. The index argument is optional (default is 1), and
322
+
performs 1-based indexing. This function is intentionally similar to the
323
+
behavior of :func:`getindex` and :func:`setindex!`
319
324
(e.g. ``[]`` access syntax).
320
325
321
326
The return value will be a new object initialized
@@ -330,21 +335,23 @@ count, but the new reference does) to ensure the memory is not prematurely freed
330
335
Note that if the object was not originally allocated by Julia, the new object
331
336
will never be finalized by Julia's garbage collector. If the ``Ptr`` itself
332
337
is actually a ``jl_value_t*``, it can be converted back to a Julia object
333
-
reference by ``unsafe_pointer_to_objref(ptr)``. (Julia values ``v``
334
-
can be converted to ``jl_value_t*`` pointers, as ``Ptr{Void}``, by calling
335
-
``pointer_from_objref(v)``.)
338
+
reference by :func:`unsafe_pointer_to_objref(ptr) <unsafe_pointer_to_objref>`.
339
+
(Julia values ``v`` can be converted to ``jl_value_t*`` pointers, as
340
+
``Ptr{Void}``, by calling :func:`pointer_from_objref(v)
341
+
<pointer_from_objref>`.)
336
342
337
-
The reverse operation (writing data to a Ptr{T}), can be performed using
338
-
``unsafe_store!(ptr, value, [index])``. Currently, this is only supported
339
-
for bitstypes or other pointer-free (``isbits``) immutable types.
343
+
The reverse operation (writing data to a ``Ptr{T}``), can be performed using
344
+
:func:`unsafe_store!(ptr, value, [index]) <unsafe_store!>`. Currently, this is
345
+
only supported for bitstypes or other pointer-free (:func:`isbits <isbits>`)
346
+
immutable types.
340
347
341
348
Any operation that throws an error is probably currently unimplemented
342
349
and should be posted as a bug so that it can be resolved.
343
350
344
351
If the pointer of interest is a plain-data array (bitstype or immutable), the
345
-
function ``pointer_to_array(ptr,dims,[own])`` may be more useful. The final
352
+
function :func:`pointer_to_array(ptr,dims,[own]) <pointer_to_array>` may be more useful. The final
346
353
parameter should be true if Julia should "take ownership" of the underlying
347
-
buffer and call ``free(ptr)`` when the returned ``Array`` object is finalized.
354
+
buffer and call :func:`free(ptr) <free>` when the returned ``Array`` object is finalized.
348
355
If the ``own`` parameter is omitted or false, the caller must ensure the
349
356
buffer remains in existence until all access is complete.
350
357
@@ -359,8 +366,8 @@ Passing Pointers for Modifying Inputs
359
366
360
367
Because C doesn't support multiple return values, often C functions will take
361
368
pointers to data that the function will modify. To accomplish this within a
362
-
``ccall`` you need to encapsulate the value inside an array of the appropriate
363
-
type. When you pass the array as an argument with a ``Ptr`` type, julia will
369
+
:func:`ccall` you need to encapsulate the value inside an array of the appropriate
370
+
type. When you pass the array as an argument with a ``Ptr`` type, Julia will
364
371
automatically pass a C pointer to the encapsulated data::
365
372
366
373
width = Cint[0]
@@ -372,21 +379,21 @@ is passed to LAPACK by reference, and on return, includes the success code.
372
379
373
380
Garbage Collection Safety
374
381
-------------------------
375
-
When passing data to a ccall, it is best to avoid using the ``pointer()``
382
+
When passing data to :func:`ccall`, it is best to avoid using the :func:`pointer`
376
383
function. Instead define a convert method and pass the variables directly to
377
-
the ccall. ccall automatically arranges that all of its arguments will be
384
+
the :func:`ccall`. :func:`ccall` automatically arranges that all of its arguments will be
378
385
preserved from garbage collection until the call returns. If a C API will
379
-
store a reference to memory allocated by Julia, after the ccall returns, you
386
+
store a reference to memory allocated by Julia, after the :func:`ccall` returns, you
380
387
must arrange that the object remains visible to the garbage collector. The
381
388
suggested way to handle this is to make a global variable of type
382
389
``Array{Any,1}`` to hold these values, until C interface notifies you that
383
390
it is finished with them.
384
391
385
392
Whenever you have created a pointer to Julia data, you must ensure the original data
386
393
exists until you are done with using the pointer. Many methods in Julia such as
387
-
``unsafe_load()`` and ``bytestring()`` make copies of data instead of taking ownership
394
+
:func:`unsafe_load` and :func:`bytestring` make copies of data instead of taking ownership
388
395
of the buffer, so that it is safe to free (or alter) the original data without
389
-
affecting Julia. A notable exception is ``pointer_to_array()`` which, for performance
396
+
affecting Julia. A notable exception is :func:`pointer_to_array` which, for performance
390
397
reasons, shares (or can be told to take ownership of) the underlying buffer.
391
398
392
399
The garbage collector does not guarantee any order of finalization. That is, if ``a``
@@ -401,35 +408,36 @@ Non-constant Function Specifications
401
408
402
409
A ``(name, library)`` function specification must be a constant expression.
403
410
However, it is possible to use computed values as function names by staging
404
-
through ``eval`` as follows::
411
+
through :func:`eval` as follows::
405
412
406
413
@eval ccall(($(string("a","b")),"lib"), ...
407
414
408
-
This expression constructs a name using ``string``, then substitutes this
409
-
name into a new ``ccall`` expression, which is then evaluated. Keep in mind that
410
-
``eval`` only operates at the top level, so within this expression local
415
+
This expression constructs a name using :func:`string`, then substitutes this
416
+
name into a new :func:`ccall` expression, which is then evaluated. Keep in mind that
417
+
:func:`eval` only operates at the top level, so within this expression local
411
418
variables will not be available (unless their values are substituted with
412
-
``$``). For this reason, ``eval`` is typically only used to form top-level
419
+
``$``). For this reason, :func:`eval` is typically only used to form top-level
413
420
definitions, for example when wrapping libraries that contain many
414
421
similar functions.
415
422
416
423
Indirect Calls
417
424
--------------
418
425
419
-
The first argument to ``ccall`` can also be an expression evaluated at
426
+
The first argument to :func:`ccall` can also be an expression evaluated at
420
427
run time. In this case, the expression must evaluate to a ``Ptr``,
421
428
which will be used as the address of the native function to call. This
422
-
behavior occurs when the first ``ccall`` argument contains references
429
+
behavior occurs when the first :func:`ccall` argument contains references
423
430
to non-constants, such as local variables or function arguments.
424
431
425
432
Calling Convention
426
433
------------------
427
434
428
-
The second argument to ``ccall`` can optionally be a calling convention
435
+
The second argument to :func:`ccall` can optionally be a calling convention
429
436
specifier (immediately preceding return type). Without any specifier,
430
437
the platform-default C calling convention is used. Other supported
431
438
conventions are: ``stdcall``, ``cdecl``, ``fastcall``, and ``thiscall``.
0 commit comments