Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Foreign function interface

From Wikipedia, the free encyclopedia
Interface to call functions from other programming languages
This article'suse ofexternal links may not follow Wikipedia's policies or guidelines. Pleaseimprove this article by removingexcessive orinappropriate external links, and converting useful links where appropriate intofootnote references.(August 2016) (Learn how and when to remove this message)

Aforeign function interface (FFI) is a mechanism by which a program written in oneprogramming language 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 binarydynamic-link library.

Naming

[edit]

The term comes from the specification forCommon Lisp, which explicitly refers to the programming language feature enabling for inter-language calls as such;[citation needed] the term is also often used officially by theinterpreter andcompilerdocumentation forHaskell,[1]Rust,[2]PHP,[3]Python, andLuaJIT (Lua)[4][5]: 35 .[6] Other languages use other terminology:Ada haslanguage bindings, whileJava hasJava Native Interface (JNI) orJava Native Access (JNA). Foreign function interface has become generic terminology for mechanisms which provide such services.

Operation

[edit]

The primary function of a foreign function interface is to mate the semantics andcalling conventions of one programming language (thehost language, or the language which defines the FFI), with the semantics and conventions of another (theguest language). This process must also take into consideration theruntime environments andapplication binary interfaces 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 compatibilitylibrary of some sort.
  • Use of a tool to automaticallywrap guest-language functions with appropriateglue code, which performs any necessary translation.
  • Use of awrapper 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 supportsgarbage 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 theJava virtual machine orJava Runtime Environment (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 avirtual machine (VM); moreover, if both are, these are often different VMs.
  • Cross-languageinheritance and other differences, such as betweentype systems or betweenobject composition models, may be especially difficult.

UML ffi.svg

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.[7]
  • C++ has a trivial FFI withC, as the languages share a significant common subset. The primary effect of theextern "C" declaration in C++ is to disable C++name mangling. With other languages, separate utils or middleware are used, examples include:
  • Clean provides a bidirectional FFI with all languages followingC or thestdcall calling convention.[8][9]
  • Common Lisp
  • Compiled Native Interface (CNI), alternative to JNI used in the GNU compiler environment.
  • One of the bases of theComponent Object Model is a common interface format, which natively uses the same types asVisual Basic for strings and arrays.
  • D does it the same way asC++ does, withextern "C" through extern (C++)
  • Dart includes dart:ffi[10] library to call nativeC code for mobile,command-line, andserver applications
  • Dynamic programming languages, such asPython,Perl,Tcl, andRuby, 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,Objective-C, andWindows COM; 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.[11] It has been improved in the Fortran 2018 standard.
  • Go can call C code directly via the"C" pseudo-package.[12]
  • Google Web Toolkit (GWT), in which Java is compiled to JavaScript, has an FFI named JSNI which allows Javasource code to call arbitrary JavaScript functions, and for JavaScript to call back into Java.
  • Haskell
  • Java Native Interface (JNI), which provides an interface betweenJava 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 writeglue code. Another example isJNR
  • LuaJIT, ajust-in-time implementation ofLua, has an FFI that allows "calling external C functions and using C data structures from pure Lua code".[4][5]: 35 
  • Nim has an FFI which enables it to use source fromC,C++, andObjective-C. It can also interface with JavaScript.
  • JavaScript usually runs insideweb browser 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.node modules that in turn may provide access to non-builtin resources.
    • Deno, provides kind of FFI interface viadlopen(...) functions.[13]
    • Bun provides a built-in module,bun:ffi, to efficiently call native libraries directly from JavaScript.[14]
  • Julia hasccall keyword to call C (and other languages, e.g., Fortran);[15] while packages, providing similar no-boilerplate support, are available for some languages e.g., for Python[16] (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 nowApache 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 information.[1],[2].
  • PHP provides FFI to C.[17]
  • Pony supports integration with C via its FFI.[18]
  • Python provides thectypes andcffi modules. For example, the ctypes module can load C functions from ashared library, ordynamic-link library (DLL) on-the-fly and translate simple data types automatically between Python and C semantics as follows:
    importctypeslibc=ctypes.CDLL('/lib/libc.so.6')# Under Linux/Unixt=libc.time(None)# Equivalent C code: t = time(NULL)print(t)
  • P/Invoke, which provides an interface between the MicrosoftCommon Language Runtime and native code.
  • Racket has a native FFI based heavily on macros that enables importing arbitrary shared libraries dynamically.[19][20]
  • Raku can callRuby,Python,Perl,Brainfuck,Lua,C,C++,Go,Scheme (Guile,Gambit), andRust[21][22]
  • Ruby provides FFI either through theffi gem, or through the standard libraryfiddle.
    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.[Fiddle::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 defines a foreign function interface to functions with various standardapplication binary interface (ABIs).[23] There is also a library for interfacing withElixir,Rustler.
  • V (Vlang) can include and supports the use of C source code and libraries.[24]
  • Visual Basic has a declarative syntax that allows it to call non-Unicode C functions.
  • Wolfram Language provides a technology named Wolfram Symbolic Transfer Protocol (WSTP) 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 builtincImport function.[25]

In addition, many FFIs can be generated automatically: for example,SWIG. However, in the case of anextension 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[26] for GIMP.[27]

Some FFIs are restricted to free standingfunctions, while others also allow calls of functions embedded in an object or class (often calledmethod calls); some even permit migration of complex datatypes or objects across the language boundary.

In most cases, an FFI is defined by ahigher-level language, so that it may employ services defined and implemented in alower-level language, typically asystem programming language likeC orC++. This is typically done to either accessoperating system (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 MicrosoftCommon Language Runtime, where a commonsubstrate 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 theJava remote method invocation (RMI), RPC,CORBA,SOAP andD-Bus permit different services to be written in different languages; such architectures are generally not considered FFIs.

Special cases

[edit]

There are some special cases, in which the languages compile into the same bytecode VM, likeClojure andJava, as well asElixir andErlang. Since there is no interface, it is not an FFI, strictly speaking, while it offers the same functions to the user.

See also

[edit]

References

[edit]
  1. ^"FFI Introduction".HaskellWiki. Retrieved19 June 2015.Haskell's FFI is used to call functions from other languages (basically C at this point), and for C to call Haskell functions.
  2. ^"std::ffi".Rust-lang.org. Retrieved1 April 2021.This module provides utilities to handle data across non-Rust interfaces, like other programming languages and the underlying operating system. It is mainly of use for FFI (Foreign Function Interface) bindings and code that needs to exchange C-like strings with other languages.
  3. ^"PHP FFI Manual".PHP Manual. Retrieved31 August 2023.Defined C variables are made available as properties of the FFI instance.
  4. ^abMike Pall."FFI Library". Luajit.org. Retrieved2013-09-29.
  5. ^abHeintz, Joachim; Hofmann, Alex; McCurdy, Iain (2013).Ways Ahead: Proceedings of the First International Csound Conference. Newcastle upon Tyne: Cambridge Scholars Publishing.ISBN 978-1-4438-5122-0.OCLC 855505215.
  6. ^"CFFI documentation". Retrieved19 June 2015.C Foreign Function Interface for Python. The goal is to provide a convenient and reliable way to call compiled C code from Python using interface declarations written in C.
  7. ^"Interface to Other Languages". Adaic.org. Retrieved2013-09-29.
  8. ^"Foreign Export". Retrieved2020-05-25.
  9. ^"Calling C From Clean". Retrieved2018-04-25.
  10. ^"dart:ffi library". Retrieved2020-01-01.
  11. ^"'fortran-iso-c-binding' tag wiki".Stack Overflow.
  12. ^"cgo".Go Programming Language. Retrieved2015-08-23.
  13. ^"Foreign Function Interface | Manual".Deno. Retrieved2023-02-08.
  14. ^"FFI API".Bun Docs.
  15. ^"Calling C and Fortran Code".JuliaLang.org. Retrieved2018-02-11.
  16. ^PyCall.jl: Package to call Python functions from the Julia language, JuliaPy, 2018-02-08, retrieved2018-02-11
  17. ^"PHP: FFI - Manual". The PHP Group. Retrieved13 June 2019.
  18. ^"Pony C-FFI Overview". Retrieved9 April 2025.
  19. ^Eli Barzilay."The Racket Foreign Interface". Docs.racket-lang.org. Retrieved2013-09-29.
  20. ^"TR600.pdf"(PDF). Archived fromthe original(PDF) on 2009-09-02. Retrieved2013-09-29.
  21. ^"Inline implementations". Retrieved2017-08-15.
  22. ^"Native Call". Retrieved2017-08-15.
  23. ^"Using extern Functions to Call External Code". Retrieved2019-06-01.
  24. ^"Including C code". Vlang. Retrieved2025-04-09.
  25. ^"Import from C Header File". Zig Software Foundation. Retrieved2021-03-11.
  26. ^"4. A sample script". Gimp.org. 2001-02-04. Retrieved2013-09-29.
  27. ^"Script-Fu and plug-ins for The GIMP". Gimp.org. Retrieved2013-09-29.

External links

[edit]
Parts,
conventions
Related topics
Retrieved from "https://en.wikipedia.org/w/index.php?title=Foreign_function_interface&oldid=1288205232"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp