A foreign function interface (FFI) is a mechanism by which a program written in one
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
can call routines or make use of services written or compiled in another one. An FFI is often used in contexts where calls are made into a binary
dynamic-link library
A dynamic-link library (DLL) is a shared library in the Microsoft Windows or OS/2 operating system. A DLL can contain executable code (functions), data, and resources.
A DLL file often has file extension .dll even though this is not required ...
.
Naming
The term comes from the specification for
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
, which explicitly refers to the programming language feature enabling for inter-language calls as such; the term is also often used officially by the
interpreter and
compiler
In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
documentation
Documentation is any communicable material that is used to describe, explain or instruct regarding some attributes of an object, system or procedure, such as its parts, assembly, installation, maintenance, and use. As a form of knowledge managem ...
for
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
,
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
,
PHP,
Python, and
LuaJIT (
Lua)
. Other languages use other terminology:
Ada has ''
language binding
In programming and software design, a binding is an application programming interface (API) that provides glue code specifically made to allow a programming language to use a foreign library or operating system service (one that is not native to ...
s'', while
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
has ''
Java Native Interface'' (JNI) or ''
Java Native Access'' (JNA). Foreign function interface has become generic terminology for mechanisms which provide such services.
Operation
The primary function of a foreign function interface is to mate the semantics and
calling conventions of one programming language (the ''host'' language, or the language which defines the FFI), with the semantics and conventions of another (the ''guest'' language). This process must also take into consideration the
runtime environment
In computer programming, a runtime system or runtime environment is a sub-system that exists in the computer where a program is created, as well as in the computers where the program is intended to be run. The name comes from the compile time ...
s and
application binary interface
An application binary interface (ABI) is an interface exposed by software that is defined for in-process machine code access. Often, the exposing software is a library, and the consumer is a program.
An ABI is at a relatively low-level of a ...
s of both. This can be done in several ways:
* Requiring that guest-language functions which are to be host-language callable be specified or implemented in a particular way, often using a compatibility
library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
of some sort.
* Use of a tool to automatically ''wrap'' guest-language functions with appropriate
glue code, which performs any necessary translation.
* Use of a
wrapper library
* Restricting the set of host language abilities which can be used cross-language. For example, C++ functions called from C may not (in general) include reference parameters or throw exceptions.
FFIs may be complicated by the following considerations:
* If one language supports
garbage collection (GC) and the other does not; care must be taken that the non-GC language code does nothing to cause GC in the other to fail. In JNI, for example, C code which "holds on to" object references that it receives from Java must communicate this information successfully to the
Java virtual machine
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally descr ...
or
Java Runtime Environment
Java is a set of computer software and specifications that provides a software platform for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms ...
(JRE), otherwise, Java may delete objects before C finishes with them. (The C code must also explicitly release its link to any such object once C has no further need of that object.)
* Complicated or non-trivial objects or datatypes may be difficult to map from one environment to another.
* It may not be possible for both languages to maintain references to the same instance of a mutable object, due to the mapping issue above.
* One or both languages may be running on a
virtual machine
In computing, a virtual machine (VM) is the virtualization or emulator, emulation of a computer system. Virtual machines are based on computer architectures and provide the functionality of a physical computer. Their implementations may involve ...
(VM); moreover, if both are, these are often different VMs.
* Cross-language
inheritance
Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offi ...
and other differences, such as between
type system
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
s or between
object composition models, may be especially difficult.

Examples of FFIs include:
*
Ada language bindings, allowing not only to call foreign functions but also to export its functions and methods to be called from non-Ada code.
*
C++ has a trivial FFI with
C, as the languages share a significant common subset. The primary effect of the declaration in C++ is to disable C++
name mangling
In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.
It provides means to e ...
. With other languages, separate utils or middleware are used, examples include:
** GNOME project:
GObject Introspection
**
SWIG
**
Chromium
Chromium is a chemical element; it has Symbol (chemistry), symbol Cr and atomic number 24. It is the first element in Group 6 element, group 6. It is a steely-grey, Luster (mineralogy), lustrous, hard, and brittle transition metal.
Chromium ...
project:
Blink and
V8 engine use an
interface description language (IDL) compiler for standard JavaScript interfaces
** Other IDL compilers
*
Clean provides a bidirectional FFI with all languages following
C or the
stdcall calling convention.
*
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
*
Compiled Native Interface (CNI), alternative to JNI used in the GNU compiler environment.
* One of the bases of the
Component Object Model
Component Object Model (COM) is a binary-interface technology for software components from Microsoft that enables using objects in a language-neutral way between different programming languages, programming contexts, processes and machines ...
is a common interface format, which natively uses the same types as
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic (.NET), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (classic), the original Visual Basic suppo ...
for strings and arrays.
*
D does it the same way as
C++ does, with
extern "C" through extern (C++)
*
Dart includes dart:ffi library to call native
C code for mobile,
command-line, and
server applications
*
Dynamic programming language
A dynamic programming language is a type of programming language that allows various operations to be determined and executed at runtime. This is different from the compilation phase. Key decisions about variables, method calls, or data types are ...
s, such as
Python,
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
,
Tcl, and
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
, all provide easy access to native code written in C, C++, or any other language obeying C/C++ calling conventions.
*
Factor has FFIs for C
Fortran an
all of these enable importing and calling arbitrary shared libraries dynamically.
*
Fortran 2003 has a module ISO_C_BINDING which provides interoperable data types (both intrinsic types and POD structs), interoperable pointers, interoperable global data stores, and mechanisms for calling C from Fortran and for calling Fortran from C. It has been improved in the Fortran 2018 standard.
*
Go can call C code directly via the
"C"
pseudo-package.
*
Google Web Toolkit
Google Web Toolkit (GWT ), or GWT Web Toolkit, is an open-source software, open-source set of Programming tool, tools that allows web developers to create and maintain JavaScript Front and back ends, front-end applications in Java (programming ...
(GWT), in which Java is compiled to JavaScript, has an FFI named JSNI which allows Java
source code
In computing, source code, or simply code or source, is a plain text computer program written in a programming language. A programmer writes the human readable source code to control the behavior of a computer.
Since a computer, at base, only ...
to call arbitrary JavaScript functions, and for JavaScript to call back into Java.
*
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
*
Java Native Interface (JNI), which provides an interface between
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
and C/C++, the preferred systems languages on most systems where Java is deployed.
Java Native Access (JNA) provides an interface with native libraries without having to write
glue code. Another example i
JNR* LuaJIT, a
just-in-time implementation of
Lua, has an FFI that allows "calling external C functions and using C data structures from pure Lua code".
*
.NET
The .NET platform (pronounced as "''dot net"'') is a free and open-source, managed code, managed computer software framework for Microsoft Windows, Windows, Linux, and macOS operating systems. The project is mainly developed by Microsoft emplo ...
have FFI through its attribute.
*
Nim has an FFI which enables it to use source from
C,
C++, and
Objective-C
Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
. It can also interface with JavaScript.
*
JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
usually runs inside
web browser
A web browser, often shortened to browser, is an application for accessing websites. When a user requests a web page from a particular website, the browser retrieves its files from a web server and then displays the page on the user's scr ...
runtimes that don't provide direct access to system libraries or commands to run, but there are few exceptions:
**
Node.js provides functions to open precompiled modules that in turn may provide access to non-builtin resources.
**
Deno, provides kind of FFI interface via functions.
**
Bun provides a built-in module,
bun:ffi
, to efficiently call native libraries directly from JavaScript.
*
Julia has
ccall
keyword to call C (and other languages, e.g., Fortran); while packages, providing similar no-boilerplate support, are available for some languages e.g., for Python (to e.g. provide OO support and GC support), Java (and supports other JDK-languages, such as Scala) and R. Interactive use with C++ is also possible with Cxx.jl package.
* PhoneGap (was named Apache Callback, but is now
Apache Cordova) is a platform for building native mobile applications using HTML, CSS and JavaScript. Also, it has FFIs via JavaScript callback functions for access to methods and properties of mobile phone's native features including accelerometer, camera (also PhotoLibrary and SavedPhotoAlbum), compass, storage (SQL database and localStorage), notification, media and capture (playing and recording or audio and video), file, contacts (address book), events, device, and connection informatio
* PHP provides FFI to C.
* Pony (programming language), Pony supports integration with C via its FFI.
* Python provides th
ctypes
an
cffi
modules. For example, the ctypes module can load C functions from a shared library
In computing, a library is a collection of System resource, resources that can be leveraged during software development to implement a computer program. Commonly, a library consists of executable code such as compiled function (computer scienc ...
, or dynamic-link library
A dynamic-link library (DLL) is a shared library in the Microsoft Windows or OS/2 operating system. A DLL can contain executable code (functions), data, and resources.
A DLL file often has file extension .dll even though this is not required ...
(DLL) on-the-fly and translate simple data types automatically between Python and C semantics as follows:
*:
import ctypes
libc = ctypes.CDLL("/lib/libc.so.6") # Under Linux/Unix
t = libc.time(None) # Equivalent C code: t = time(NULL)
print(t)
* P/Invoke, which provides an interface between the Microsoft Common Language Runtime
The Common Language Runtime (CLR), the virtual machine component of Microsoft .NET Framework, manages the execution of .NET programs. Just-in-time compilation converts the managed code (compiled intermediate language code) into machine instr ...
and native code.
* Racket has a native FFI based heavily on macros that enables importing arbitrary shared libraries dynamically.
* Raku can call Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
, Python, Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
, Brainfuck, Lua, C, C++, Go, Scheme ( Guile, Gambit), and Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
* Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
provides FFI either through th
ffi
gem, or through the standard librar
*:
require 'fiddle'
libm = Fiddle.dlopen('/lib/libm.so.6')
# Equivalent to: double floor(double x);
floor = Fiddle::Function.new(
libm.sym('floor'), # ptr is a referenced function(, or symbol), of a Fiddle::Handle.
iddle::TYPE_DOUBLE # args is an Array of arguments, passed to the ptr function.
Fiddle::TYPE_DOUBLE # ret_type is the return type of the function
)
# Equivalent to: floor(3.14159);
floor.call(3.14159) #=> 3.0
* Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
defines a foreign function interface to functions with various standard application binary interface
An application binary interface (ABI) is an interface exposed by software that is defined for in-process machine code access. Often, the exposing software is a library, and the consumer is a program.
An ABI is at a relatively low-level of a ...
(ABIs). There is also a library for interfacing with Elixir
An elixir is a sweet liquid used for medical purposes, to be taken orally and intended to cure one's illness. When used as a dosage form, pharmaceutical preparation, an elixir contains at least one active ingredient designed to be taken orall ...
Rustler
* V (Vlang) can include and supports the use of C source code and libraries.
* Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic (.NET), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (classic), the original Visual Basic suppo ...
has a declarative syntax that allows it to call non-Unicode C functions.
* Wolfram Language
The Wolfram Language ( ) is a proprietary, very high-level multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary stru ...
provides a technology named Wolfram Symbolic Transfer Protocol (WSTP) which enables bidirectional calling of code between other languages with bindings for C++, Java, .NET
The .NET platform (pronounced as "''dot net"'') is a free and open-source, managed code, managed computer software framework for Microsoft Windows, Windows, Linux, and macOS operating systems. The project is mainly developed by Microsoft emplo ...
. and other languages.
* Zig provides FFI to C using the builtin function.
In addition, many FFIs can be generated automatically: for example, SWIG. However, in the case of an extension language a semantic inversion of the relationship of guest and host can occur, when a smaller body of extension language is the guest invoking services in the larger body of host language, such as writing a small plugin for GIMP.
Some FFIs are restricted to free standing functions, while others also allow calls of functions embedded in an object or class (often called method calls); some even permit migration of complex datatypes or objects across the language boundary.
In most cases, an FFI is defined by a higher-level language, so that it may employ services defined and implemented in a lower-level language, typically a system programming language
A system programming language is a programming language used for system programming; such languages are designed for writing system software, which usually requires different development approaches when compared with application software. Eds ...
like C or C++. This is typically done to either access operating system
An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ...
(OS) services in the language in which the OS API is defined, or for performance goals.
Many FFIs also provide the means for the called language to invoke services in the host language also.
The term foreign function interface is generally not used to describe multi-lingual runtimes such as the Microsoft Common Language Runtime
The Common Language Runtime (CLR), the virtual machine component of Microsoft .NET Framework, manages the execution of .NET programs. Just-in-time compilation converts the managed code (compiled intermediate language code) into machine instr ...
, where a common ''substrate'' is provided which enables any CLR-compliant language to use services defined in any other. (However, in this case the CLR does include an FFI, P/Invoke, to call outside the runtime.) In addition, many distributed computing architectures such as the Java remote method invocation (RMI), RPC, CORBA
The Common Object Request Broker Architecture (CORBA) is a standard defined by the Object Management Group (OMG) designed to facilitate the communication of systems that are deployed on diverse platforms. CORBA enables collaboration between sy ...
, SOAP
Soap is a salt (chemistry), salt of a fatty acid (sometimes other carboxylic acids) used for cleaning and lubricating products as well as other applications. In a domestic setting, soaps, specifically "toilet soaps", are surfactants usually u ...
and D-Bus
D-Bus (short for "Desktop Bus")
is a message-oriented middleware mechanism that allows communication between multiple Process (computing), processes running concurrently on the same machine. D-Bus was developed as part of the freedesktop.org pro ...
permit different services to be written in different languages; such architectures are generally not considered FFIs.
Special cases
There are some special cases, in which the languages compile into the same bytecode VM, like
Clojure
Clojure (, like ''closure'') is a dynamic programming language, dynamic and functional programming, functional dialect (computing), dialect of the programming language Lisp (programming language), Lisp on the Java (software platform), Java platfo ...
and
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, as well as
Elixir
An elixir is a sweet liquid used for medical purposes, to be taken orally and intended to cure one's illness. When used as a dosage form, pharmaceutical preparation, an elixir contains at least one active ingredient designed to be taken orall ...
and
Erlang. Since there is no interface, it is not an FFI, strictly speaking, while it offers the same functions to the user.
See also
*
Language interoperability
*
Interface definition language
An interface description language or interface definition language (IDL) is a generic term for a language that lets a program or object written in one language communicate with another program written in an unknown language. IDLs are usually use ...
*
Calling convention
*
Name mangling
In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.
It provides means to e ...
*
Application programming interface
An application programming interface (API) is a connection between computers or between computer programs. It is a type of software Interface (computing), interface, offering a service to other pieces of software. A document or standard that des ...
*
Application binary interface
An application binary interface (ABI) is an interface exposed by software that is defined for in-process machine code access. Often, the exposing software is a library, and the consumer is a program.
An ABI is at a relatively low-level of a ...
*
Comparison of application virtual machines
*
SWIG
*
Remote procedure call
In distributed computing, a remote procedure call (RPC) is when a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared computer network), which is written as if it were a ...
*
libffi
References
External links
c2.com: Foreign function interfaceHaskell 98 Foreign Function Interface
{{Application binary interface
Application programming interfaces
Subroutines