Foreign Function Interface
   HOME

TheInfoList



OR:

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 ...
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 fro ...
, which explicitly refers to the language features for inter-language calls as such; the term is also used officially by the
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 has pioneered a number of programming lan ...
,
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 Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
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, expl ...
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 th ...
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 List ...
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 Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface (JNI). JNA's design aims to provide native access in a natural way with a minimum ...
). 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 been ...
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 t ...
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 Adhesive, also known as glue, cement, mucilage, or paste, is any non-metallic substance applied to one or both surfaces of two separate items that binds them together and resists their separation. The use of adhesives offers certain advant ...
, 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 Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclabl ...
(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 cros ...
(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 hardw ...
(VM); moreover, if both are, these will probably be different VMs. * Cross-language
inheritance Inheritance is the practice of receiving private property, Title (property), titles, debts, entitlements, Privilege (law), privileges, rights, and Law of obligations, obligations upon the death of an individual. The rules of inheritance differ ...
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 Ada may refer to: Places Africa * Ada Foah, a town in Ghana * Ada (Ghana parliament constituency) * Ada, Osun, a town in Nigeria Asia * Ada, Urmia, a village in West Azerbaijan Province, Iran * Ada, Karaman, a village in Karaman Province, ...
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++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
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 a way of e ...
. * 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 ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
* 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++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
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 thi ...
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 * Dar ...
includes dart:ffi library to call native C code for mobile, command-line, and server applications *
Dynamic language In computer science, a dynamic programming language is a class of high-level programming languages, which at runtime execute many common programming behaviours that static programming languages perform during compilation. These behaviors cou ...
s, such as
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
,
Tcl TCL or Tcl or TCLs may refer to: Business * TCL Technology, a Chinese consumer electronics and appliance company **TCL Electronics, a subsidiary of TCL Technology * Texas Collegiate League, a collegiate baseball league * Trade Centre Limited ...
, 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 sa ...
, 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, suc ...
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 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 has pioneered a number of programming lan ...
*
JNI In software design, the Java Native Interface (JNI) is a foreign function interface programming software framework, framework that enables Java (programming language), Java code running in a Java virtual machine (JVM) to call and be called by n ...
, 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 List ...
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 Adhesive, also known as glue, cement, mucilage, or paste, is any non-metallic substance applied to one or both surfaces of two separate items that binds them together and resists their separation. The use of adhesives offers certain advant ...
. 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 has an FFI which enables it to use source from C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, 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 NeXTS ...
. 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.g ...
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 Apache Cordova (formerly PhoneGap) is a mobile application development framework created by Nitobi. Adobe Systems purchased Nitobi in 2011, rebranded it as PhoneGap, and later released an open-source version of the software called Apache Cordov ...
(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 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 implementation is now produced by The PHP Group. ...
provides FFI to C. *
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
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 Platform Invocation Services, commonly referred to as P/Invoke, is a feature of Common Language Infrastructure implementations, like Microsoft's Common Language Runtime, that enables managed code to call native code. Managed code, such as C# or ...
, 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 instructio ...
and native code. * Racket 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 sa ...
,
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
,
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++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, 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 chara ...
/
Gambit A gambit (from Italian , the act of tripping someone with the leg to make them fall) is a chess opening in which a player sacrifices with the aim of achieving a subsequent advantage. The word '' gambit'' is also sometimes used to describe sim ...
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 sa ...
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 (cl ...
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 ...
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 scripting ...
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
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
s, while others also allow calls of functions embedded in an object or class (often called method calls); 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++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
. 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 instructio ...
, 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 Platform Invocation Services, commonly referred to as P/Invoke, is a feature of Common Language Infrastructure implementations, like Microsoft's Common Language Runtime, that enables managed code to call native code. Managed code, such as C# or ...
, to call outside the runtime.) In addition, many distributed computing architectures such as the
Java remote method invocation In computing, the Java Remote Method Invocation (Java RMI) is a Java API that performs remote method invocation, the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and dist ...
(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 sys ...
,
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 use ...
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 comm ...
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 List ...
, 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 Language interoperability is the capability of two different programming languages to natively interact as part of the same system and operate on the same kind of data structures. There are many ways programming languages are interoperable with on ...
*
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 been ...
*
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 a way of e ...
*
Application programming interface An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how t ...
*
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 Application virtualization software refers to both application virtual machines and software responsible for implementing them. Application virtual machines are typically used to allow application bytecode to run portably on many different comput ...
* 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 (l ...
*
libffi libffi is a foreign function interface library. It provides a C programming language interface for calling natively compiled functions given information about the target function at run time instead of compile time. It also implements the oppos ...


References


External links


c2.com: Foreign function interface

Haskell 98 Foreign Function Interface



A Foreign Function Interface generator for occam-pi

UFFI: Lisp Universal Foreign Function Interface

CFFI: Common Foreign Function Interface, for Common Lisp

Java 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 conventions

FFCALL

C/Invoke

libffi
Application programming interfaces Subroutines