<commit_before>.. _ffi:

Foreign function interface (FFI)
================================

.. index::
   single: -XForeignFunctionInterface
   single: Foreign function interface
   single: interfacing with native code

GHC (mostly) conforms to the Haskell Foreign Function Interface, whose
definition is part of the Haskell Report on
`http://www.haskell.org/ <http://www.haskell.org/>`__.

FFI support is enabled by default, but can be enabled or disabled
explicitly with the :ghc-flag:`-XForeignFunctionInterface` flag.

GHC implements a number of GHC-specific extensions to the FFI Addendum.
These extensions are described in :ref:`ffi-ghcexts`, but please note
that programs using these features are not portable. Hence, these
features should be avoided where possible.

The FFI libraries are documented in the accompanying library
documentation; see for example the :base-ref:`Foreign <Foreign.html>` module.

GHC differences to the FFI Addendum
-----------------------------------

Guaranteed call safety
~~~~~~~~~~~~~~~~~~~~~~

The FFI addendum stipulates that an implementation is free to implement an
``unsafe`` call by performing a ``safe`` call (and therefore may run in an
arbitrary thread and may be subject to concurrent garbage collection). This
greatly constrains library authors since it implies that it is never safe to
pass any heap object reference to a foreign function, even if invoked with an
``unsafe`` call. For instance, it is often desirable to pass an unpinned
``ByteArray#``\s directly to native code to avoid making an
otherwise-unnecessary copy. However, this can only be done safely under
``unsafe`` call semantics as otherwise the array may be moved by the garbage
collector in the middle of the call.

In previous releases, GHC would take advantage of the freedom afforded by the
Addendum by performing ``safe`` foreign calls in place of ``unsafe`` calls in
the bytecode interpreter. This meant that some packages which worked when
compiled would fail under GHCi (e.g. :ghc-ticket:`13730`).

However, since version 8.4 this is no longer the case: GHC **guarantees** that
garbage collection will never occur during an ``unsafe`` call, even in the
bytecode interpreter.


.. _ffi-ghcexts:

GHC extensions to the FFI Addendum
----------------------------------

The FFI features that are described in this section are specific to GHC.
Your code will not be portable to other compilers if you use them.

Unboxed types
~~~~~~~~~~~~~

The following unboxed types may be used as basic foreign types (see FFI
Addendum, Section 3.2): ``Int#``, ``Word#``, ``Char#``, ``Float#``,
``Double#``, ``Addr#``, ``StablePtr# a``, ``MutableByteArray#``,
``ForeignObj#``, and ``ByteArray#``.

.. _ffi-newtype-io:

Newtype wrapping of the IO monad
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The FFI spec requires the IO monad to appear in various places, but it
can sometimes be convenient to wrap the IO monad in a ``newtype``, thus: ::

      newtype MyIO a = MIO (IO a)

(A reason for doing so might be to prevent the programmer from calling
arbitrary IO procedures in some part of the program.)

The Haskell FFI already specifies that arguments and results of foreign
imports and exports will be automatically unwrapped if they are newtypes
(Section 3.2 of the FFI addendum). GHC extends the FFI by automatically
unwrapping any newtypes that wrap the IO monad itself. More precisely,
wherever the FFI specification requires an ``IO`` type, GHC will accept any
newtype-wrapping of an ``IO`` type. For example, these declarations are
OK: ::

       foreign import foo :: Int -> MyIO Int
       foreign import "dynamic" baz :: (Int -> MyIO Int) -> CInt -> MyIO Int

.. _ffi-prim:<commit_msg>user-guide: Various fixes to FFI section<commit_after>.. _ffi:

Foreign function interface (FFI)
================================

.. index::
   single: -XForeignFunctionInterface
   single: Foreign function interface
   single: interfacing with native code

GHC (mostly) conforms to the Haskell Foreign Function Interface, whose
definition is part of the Haskell Report on
`http://www.haskell.org/ <http://www.haskell.org/>`__.

FFI support is enabled by default, but can be enabled or disabled
explicitly with the :ghc-flag:`-XForeignFunctionInterface` flag.

GHC implements a number of GHC-specific extensions to the FFI Chapter of the
Haskell 2010 Report. These extensions are described in :ref:`ffi-ghcexts`, but
please note that programs using these features are not portable. Hence, these
features should be avoided where possible.

The FFI libraries are documented in the accompanying library
documentation; see for example the :base-ref:`Foreign <Foreign.html>` module.

GHC differences to the FFI Chapter
----------------------------------

Guaranteed call safety
~~~~~~~~~~~~~~~~~~~~~~

The FFI addendum stipulates that an implementation is free to implement an
``unsafe`` call by performing a ``safe`` call (and therefore may run in an
arbitrary thread and may be subject to concurrent garbage collection). This
greatly constrains library authors since it implies that it is never safe to
pass any heap object reference to a foreign function, even if invoked with an
``unsafe`` call. For instance, it is often desirable to pass an unpinned
``ByteArray#``\s directly to native code to avoid making an
otherwise-unnecessary copy. However, this can only be done safely under
``unsafe`` call semantics as otherwise the array may be moved by the garbage
collector in the middle of the call.

In previous releases, GHC would take advantage of the freedom afforded by the
Chapter by performing ``safe`` foreign calls in place of ``unsafe`` calls in
the bytecode interpreter. This meant that some packages which worked when
compiled would fail under GHCi (e.g. :ghc-ticket:`13730`).

However, since version 8.4 this is no longer the case: GHC **guarantees** that
garbage collection will never occur during an ``unsafe`` call, even in the
bytecode interpreter.


.. _ffi-ghcexts:

GHC extensions to the FFI Chapter
---------------------------------

The FFI features that are described in this section are specific to GHC.
Your code will not be portable to other compilers if you use them.

Unboxed types
~~~~~~~~~~~~~

The following unboxed types may be used as basic foreign types (see FFI
Chapter, Section 8.6): ``Int#``, ``Word#``, ``Char#``, ``Float#``,
``Double#``, ``Addr#``, ``StablePtr# a``, ``MutableByteArray#``,
``ForeignObj#``, and ``ByteArray#``.

.. _ffi-newtype-io:

Newtype wrapping of the IO monad
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The FFI spec requires the IO monad to appear in various places, but it
can sometimes be convenient to wrap the IO monad in a ``newtype``, thus: ::

      newtype MyIO a = MIO (IO a)

(A reason for doing so might be to prevent the programmer from calling
arbitrary IO procedures in some part of the program.)

The Haskell FFI already specifies that arguments and results of foreign
imports and exports will be automatically unwrapped if they are newtypes
(Section 3.2 of the FFI addendum). GHC extends the FFI by automatically
unwrapping any newtypes that wrap the IO monad itself. More precisely,
wherever the FFI specification requires an ``IO`` type, GHC will accept any
newtype-wrapping of an ``IO`` type. For example, these declarations are
OK: ::

       foreign import foo :: Int -> MyIO Int
       foreign import "dynamic" baz :: (Int -> MyIO Int) -> CInt -> MyIO Int

.. _ffi-prim:
{'fraction_non_alphanumeric': 0.11563802608578728, 'fraction_numerical': 0.0034960333467796154, 'mean_word_length': 4.158113730929265, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5082765', 'n_tokens_mistral': 2037, 'n_tokens_neox': 1925, 'n_words': 1031}