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. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
can call routines or make use of services written in another.
Naming
The term comes from the specification for
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
, which explicitly refers to the language features for inter-language calls as such; the term is also used officially by the
Haskell,
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), ...
, and
Python programming languages. Other languages use other terminology: the
Ada programming language
Ada is a structured, statically typed, imperative, and object-oriented high-level programming language, extended from Pascal and other languages. It has built-in language support for '' design by contract'' (DbC), extremely strong typing, ex ...
talks about "
language binding
In programming and software design, 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 (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
refers to its FFI as the JNI (
Java Native Interface
In software design, the Java Native Interface (JNI) is a foreign function interface programming framework that enables Java code running in a Java virtual machine (JVM) to call and be called by
native applications (programs specific to a hardwa ...
) or JNA (
Java Native Access). 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 convention
In computer science, a calling convention is an implementation-level (low-level) scheme for how subroutines or functions receive parameters from their caller and how they return a result. When some code calls a function, design choices have b ...
s 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 both 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 ...
s and/or
application binary interface
In computer software, an application binary interface (ABI) is an interface between two binary program modules. Often, one of these modules is a library or operating system facility, and the other is a program that is being run by a user.
An ...
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 of some sort.
* Use of a tool to automatically "wrap" guest-language functions with appropriate
glue code, which performs any necessary translation.
* Use of
wrapper libraries
* Restricting the set of host language capabilities 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 "register" this fact with the
Java runtime environment
Java is a set of computer software and specifications developed by James Gosling at Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a c ...
(JRE); otherwise, Java may delete objects before C has finished 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/ emulation of a computer system. Virtual machines are based on computer architectures and provide functionality of a physical computer. Their implementations may involve specialized har ...
(VM); moreover, if both are, these will probably be 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. Offici ...
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 to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
s or between
object-composition models, may be especially difficult.
By language
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.
*
Clean provides a bidirectional FFI with all languages following
C or the
stdcall
This article describes the calling conventions used when programming x86 architecture microprocessors.
Calling conventions describe the interface of called code:
*The order in which atomic (scalar) parameters, or individual parts of a complex pa ...
calling convention.
*
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
*
CNI, alternative to JNI used in the GNU compiler environment.
* One of the bases of the
Component Object Model is a common interface format, which natively uses the same types as Visual Basic for strings and arrays.
*
D does it the same way as
C++ does, with
extern "C"
The C and C++ programming languages are closely related but have many significant differences. C++ began as a fork of an early, pre- standardized C, and was designed to be mostly source-and-link compatible with C compilers of the time. Due to ...
through extern (C++)
*
Dart
Dart or DART may refer to:
* Dart, the equipment in the game of darts
Arts, entertainment and media
* Dart (comics), an Image Comics superhero
* Dart, a character from ''G.I. Joe''
* Dart, a ''Thomas & Friends'' railway engine character
* D ...
includes dart:ffi library to call native
C code for mobile, command-line, and server applications
*
Dynamic languages, such as
Python,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
,
Tcl, and
Ruby
A 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 sapp ...
, all provide easy access to native code written in C/C++ (or any other language obeying C/C++ calling conventions).
*
Factor
Factor, a Latin word meaning "who/which acts", may refer to:
Commerce
* Factor (agent), a person who acts for, notably a mercantile and colonial agent
* Factor (Scotland), a person or firm managing a Scottish estate
* Factors of production, ...
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.
*
GWT, in which Java is compiled to JavaScript, has an FFI called JSNI which allows Java source to call arbitrary JavaScript functions, and for JavaScript to call back into Java.
*
Haskell
*
JNI, which provides an interface between
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
and C/C++, the preferred systems languages on most systems where Java is deployed.
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
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
, has an FFI that allows "calling external C functions and using C data structures from pure Lua code".
*
Nim
Nim is a mathematical two player game.
Nim or NIM may also refer to:
* Nim (programming language)
* Nim Chimpsky, a signing chimpanzee Acronyms
* Network Installation Manager, an IBM framework
* Nuclear Instrumentation Module
* Negative index met ...
has an FFI which enables it to use source from
C,
C++, and
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its N ...
. It can also interface with Javascript.
*
Julia
Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e ...
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 called by the name Apache Callback, but now Apache Cordova) is a platform for building native mobile applications using HTML, CSS and JavaScript. Additionally 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
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
provides FFI to C.
* Python provides th
ctypes
an
cffi
modules. For example, the ctypes module can load C functions from shared libraries
In computer science, a library is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and su ...
/ DLLs 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 instruc ...
and native code.
* Racket
Racket may refer to:
* Racket (crime), a systematised element of organized crime
** Protection racket, a scheme whereby a group provides protection to businesses or other groups through violence outside the sanction of the law
* Racket (sports equ ...
has a native FFI based heavily on macros that enables importing arbitrary shared libraries dynamically.
* Raku can call Ruby
A 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 sapp ...
, Python, Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
, Brainfuck
Brainfuck is an esoteric programming language created in 1993 by Urban Müller.
Notable for its extreme minimalism, the language consists of only eight simple commands, a data pointer and an instruction pointer. While it is fully Turing com ...
, Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
, C, C++, Go, Scheme Guile
Guile may refer to:
* Astuteness, deception.
* GNU Guile, an implementation of the Scheme programming language
* Guile (''Street Fighter''), a video game character from the ''Street Fighter'' series
* Guile (''Chrono Cross''), a video game char ...
/ 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
A 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 sapp ...
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 ABIs. There is also a library for interfacing with Elixir
ELIXIR (the European life-sciences Infrastructure for biological Information) is an initiative that will allow life science laboratories across Europe to share and store their research data as part of an organised network. Its goal is to bring t ...
Rustler
* Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (c ...
has a declarative syntax that allows it to call non-Unicode C functions.
* Wolfram Language
The Wolfram Language ( ) is a general multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary structures and data. It is ...
provides a technology called WSTP (Wolfram Symbolic Transfer Protocol) which enables bidirectional calling of code between other languages with bindings for C++, Java, .NET 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 scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled.
A scriptin ...
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 call
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
s); some even permit migration of complex datatypes and/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 systems language like C or C++. This is typically done to either access OS services in the language in which the OS' API is defined, or for performance considerations.
Many FFIs also provide the means for the called language to invoke services in the host language as well.
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 instruc ...
, 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 of a fatty acid used in a variety of cleansing and lubricating products. In a domestic setting, soaps are surfactants usually used for washing, bathing, and other types of housekeeping. In industrial settings, soaps are used ...
and D-Bus
In computing, D-Bus (short for "Desktop Bus")
is a message-oriented middleware mechanism that allows communication between multiple processes running concurrently on the same machine. D-Bus was developed as part of the freedesktop.org project, ...
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 and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is ...
and
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, as well as
Elixir
ELIXIR (the European life-sciences Infrastructure for biological Information) is an initiative that will allow life science laboratories across Europe to share and store their research data as part of an organised network. Its goal is to bring t ...
and
Erlang. Since there is no interface, it is not an FFI, strictly speaking, while it offers the same functionality to the user.
See also
*
Language interoperability
*
Interface definition language
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 describe an inter ...
*
Calling convention
In computer science, a calling convention is an implementation-level (low-level) scheme for how subroutines or functions receive parameters from their caller and how they return a result. When some code calls a function, design choices have b ...
*
Name mangling
*
Application programming interface
*
Application binary interface
In computer software, an application binary interface (ABI) is an interface between two binary program modules. Often, one of these modules is a library or operating system facility, and the other is a program that is being run by a user.
An ...
*
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 network), which is coded as if it were a normal (lo ...
*
libffi
References
External links
c2.com: Foreign function interfaceHaskell 98 Foreign Function InterfaceA Foreign Function Interface generator for occam-piUFFI: Lisp Universal Foreign Function InterfaceCFFI: Common Foreign Function Interface, for Common LispJava Native Interface: Programmer's Guide and Specification* {{Javadoc:SE-guide, jni/spec/jniTOC.html, The JNI Specification
dyncall library using assembly call kernels for a variety of processors,OS and calling conventionsFFCALLC/Invokelibffi
Application programming interfaces
Subroutines