Call a foreign-language function: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 17: Line 17:
*   [[Use another language to call a function]]
*   [[Use another language to call a function]]
<br><br>
<br><br>
=={{header|8th}}==

<syntaxhighlight lang="forth">
\ tell 8th what the function expects:
"ZZ" "strdup" func: strdup
"VZ" "free" func: free
\ call the external funcs
"abc" dup \ now we have two strings "abc" on the stack
strdup .s cr \ after strdup, you'll have the new (but duplicate) string on the stack
\ the ".s" will show both strings and you can see they are different items on the stack
free \ let the c library free the string
</syntaxhighlight>
=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
{{works with|Sega Genesis}}
{{works with|Sega Genesis}}
Line 26: Line 36:


'''Z80 Code:'''
'''Z80 Code:'''
<syntaxhighlight lang=z80>org &0000 ;execution resets here after the 68000 resets the Z80 and sends a bus request.
<syntaxhighlight lang="z80">org &0000 ;execution resets here after the 68000 resets the Z80 and sends a bus request.
jr start
jr start


Line 59: Line 69:
Here's the 68000 code that will get the Z80 to call this function:
Here's the 68000 code that will get the Z80 to call this function:


<syntaxhighlight lang=68000devpac>Z80_Call:
<syntaxhighlight lang="68000devpac">Z80_Call:
MOVE.W #$100,$A11100 ;write: z80 reset
MOVE.W #$100,$A11100 ;write: z80 reset
.wait:
.wait:
Line 75: Line 85:
MOVE.B #$FF,$A01F01 ;unlock the semaphore
MOVE.B #$FF,$A01F01 ;unlock the semaphore
MOVE.W #0,$A11100 ;Z80 Bus Request - after this write, the Z80 will start executing code.</syntaxhighlight>
MOVE.W #0,$A11100 ;Z80 Bus Request - after this write, the Z80 will start executing code.</syntaxhighlight>

=={{header|8th}}==
<syntaxhighlight lang=forth>
\ tell 8th what the function expects:
"ZZ" "strdup" func: strdup
"VZ" "free" func: free
\ call the external funcs
"abc" dup \ now we have two strings "abc" on the stack
strdup .s cr \ after strdup, you'll have the new (but duplicate) string on the stack
\ the ".s" will show both strings and you can see they are different items on the stack
free \ let the c library free the string
</syntaxhighlight>

=={{header|Ada}}==
=={{header|Ada}}==
Ada provides standard interfaces to [[C]], [[C++]], [[Fortran]] and [[Cobol]]. Other language interfaces can be provided as well, but are not mandatory. Usually it is possible to communicate to any language that supports calling conventions standard to the [[OS]] ('''cdecl''', '''stdcall''' etc).
Ada provides standard interfaces to [[C]], [[C++]], [[Fortran]] and [[Cobol]]. Other language interfaces can be provided as well, but are not mandatory. Usually it is possible to communicate to any language that supports calling conventions standard to the [[OS]] ('''cdecl''', '''stdcall''' etc).
<syntaxhighlight lang=Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C; use Interfaces.C;
with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with Interfaces.C.Strings; use Interfaces.C.Strings;
Line 105: Line 102:
Free (S2);
Free (S2);
end Test_C_Interface;</syntaxhighlight>
end Test_C_Interface;</syntaxhighlight>

=={{header|Aikido}}==
=={{header|Aikido}}==
There are two ways to call a <em>native</em> function in Aikido. The first is to write a wrapper function in C++ that is invoked from the Aikido interpreter. In a C++ file:
There are two ways to call a <em>native</em> function in Aikido. The first is to write a wrapper function in C++ that is invoked from the Aikido interpreter. In a C++ file:
<syntaxhighlight lang=aikido>#include <aikido.h>
<syntaxhighlight lang="aikido">#include <aikido.h>
extern "C" { // need C linkage
extern "C" { // need C linkage


Line 123: Line 119:


Then in the Aikido program:
Then in the Aikido program:
<syntaxhighlight lang=aikido>native function strdup(s)
<syntaxhighlight lang="aikido">native function strdup(s)
println (strdup ("Hello World!"))</syntaxhighlight>
println (strdup ("Hello World!"))</syntaxhighlight>


The second way is to use a <em>raw native</em> function. These functions must adhere to a defined set of rules and can be called directly from the Aikido interpreter. In the case of <code>strdup</code> we need to play a nasty trick because it returns a pointer that we need to print as a string.
The second way is to use a <em>raw native</em> function. These functions must adhere to a defined set of rules and can be called directly from the Aikido interpreter. In the case of <code>strdup</code> we need to play a nasty trick because it returns a pointer that we need to print as a string.


<syntaxhighlight lang=aikido>native function strdup (s) // declare native
<syntaxhighlight lang="aikido">native function strdup (s) // declare native
native function free(p) // also need to free the result
native function free(p) // also need to free the result


Line 142: Line 138:
}
}
free (s) // done with the memory now</syntaxhighlight>
free (s) // done with the memory now</syntaxhighlight>

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
The designers of Algol 68 made it extremely hard to incorporate code written in other languages. To be fair, this was a long time ago when such considerations weren't thought important and one should be careful to apply Hanlon's razor.
The designers of Algol 68 made it extremely hard to incorporate code written in other languages. To be fair, this was a long time ago when such considerations weren't thought important and one should be careful to apply Hanlon's razor.
Line 149: Line 144:


Note that I chose a non-trivial library function because the suggested strdup() doesn't really demonstrate the technique all that well.
Note that I chose a non-trivial library function because the suggested strdup() doesn't really demonstrate the technique all that well.
<syntaxhighlight lang=algol68>
<syntaxhighlight lang="algol68">
BEGIN
BEGIN
MODE PASSWD = STRUCT (STRING name, passwd, INT uid, gid, STRING gecos, dir, shell);
MODE PASSWD = STRUCT (STRING name, passwd, INT uid, gid, STRING gecos, dir, shell);
Line 222: Line 217:
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
</pre>
</pre>

=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 280: Line 274:
bx lr @ return
bx lr @ return
</syntaxhighlight>
</syntaxhighlight>

=={{header|Arturo}}==
=={{header|Arturo}}==


'''C Library'''
'''C Library'''


<syntaxhighlight lang=c>// compile with:
<syntaxhighlight lang="c">// compile with:
// clang -c -w mylib.c
// clang -c -w mylib.c
// clang -shared -o libmylib.dylib mylib.o
// clang -shared -o libmylib.dylib mylib.o
Line 301: Line 294:
'''Calling from Arturo'''
'''Calling from Arturo'''


<syntaxhighlight lang=rebol>; call an external function directly
<syntaxhighlight lang="rebol">; call an external function directly
call.external: "mylib" 'sayHello ["John"]
call.external: "mylib" 'sayHello ["John"]


Line 322: Line 315:
The double of 2 is 4
The double of 2 is 4
The double of 3 is 6 </pre>
The double of 3 is 6 </pre>

=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
from the documentation for dllcall: <syntaxhighlight lang=AutoHotkey>; Example: Calls the Windows API function "MessageBox" and report which button the user presses.
from the documentation for dllcall: <syntaxhighlight lang="autohotkey">; Example: Calls the Windows API function "MessageBox" and report which button the user presses.


WhichButton := DllCall("MessageBox", "int", "0", "str", "Press Yes or No", "str", "Title of box", "int", 4)
WhichButton := DllCall("MessageBox", "int", "0", "str", "Press Yes or No", "str", "Title of box", "int", 4)
MsgBox You pressed button #%WhichButton%.</syntaxhighlight>
MsgBox You pressed button #%WhichButton%.</syntaxhighlight>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang=bbcbasic> SYS "LoadLibrary", "MSVCRT.DLL" TO msvcrt%
<syntaxhighlight lang="bbcbasic"> SYS "LoadLibrary", "MSVCRT.DLL" TO msvcrt%
SYS "GetProcAddress", msvcrt%, "_strdup" TO `strdup`
SYS "GetProcAddress", msvcrt%, "_strdup" TO `strdup`
SYS "GetProcAddress", msvcrt%, "free" TO `free`
SYS "GetProcAddress", msvcrt%, "free" TO `free`
Line 339: Line 330:
SYS `free`, address%
SYS `free`, address%
</syntaxhighlight>
</syntaxhighlight>

=={{header|C}}==
=={{header|C}}==
===Assembly via GCC===
===Assembly via GCC===
Assembly code can be embedded and compiled via GCC.
Assembly code can be embedded and compiled via GCC.
<syntaxhighlight lang=C>
<syntaxhighlight lang="c">
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
Line 381: Line 371:
===Python===
===Python===
'''IMPORTANT''' : The following implementation has been tested against Python 2.7, this won't work on a system which does not have the relevant files installed. Also pay attention to the compilation flags.
'''IMPORTANT''' : The following implementation has been tested against Python 2.7, this won't work on a system which does not have the relevant files installed. Also pay attention to the compilation flags.
<syntaxhighlight lang=C>#include <python2.7/Python.h>
<syntaxhighlight lang="c">#include <python2.7/Python.h>


int main()
int main()
Line 408: Line 398:
First 10 multiples of 3 in reverse order : [30, 27, 24, 21, 18, 15, 12, 9, 6, 3]
First 10 multiples of 3 in reverse order : [30, 27, 24, 21, 18, 15, 12, 9, 6, 3]
</pre>
</pre>

=={{header|C++}}==
=={{header|C++}}==
While calling C functions from C++ is generally almost trivial, <code>strdup</code> illustrates some fine point in communicating with C libraries. However, to illustrate how to generally use C functions, a C function <code>strdup1</code> is used, which is assumed to have the same interface and behaviour as strdup, but cannot be found in a standard header.
While calling C functions from C++ is generally almost trivial, <code>strdup</code> illustrates some fine point in communicating with C libraries. However, to illustrate how to generally use C functions, a C function <code>strdup1</code> is used, which is assumed to have the same interface and behaviour as strdup, but cannot be found in a standard header.


In addition, this code demonstrates a call to a FORTRAN function defined as
In addition, this code demonstrates a call to a FORTRAN function defined as
<syntaxhighlight lang=cpp>FUNCTION MULTIPLY(X, Y)
<syntaxhighlight lang="cpp">FUNCTION MULTIPLY(X, Y)
DOUBLE PRECISION MULTIPLY, X, Y</syntaxhighlight>
DOUBLE PRECISION MULTIPLY, X, Y</syntaxhighlight>
Note that the calling convention of FORTRAN depends on the system and the used FORTRAN compiler, and sometimes even on the command line options used for the compiler; here, GNU Fortran with no options is assumed.
Note that the calling convention of FORTRAN depends on the system and the used FORTRAN compiler, and sometimes even on the command line options used for the compiler; here, GNU Fortran with no options is assumed.
<syntaxhighlight lang=cpp>#include <cstdlib> // for C memory management
<syntaxhighlight lang="cpp">#include <cstdlib> // for C memory management
#include <string> // for C++ strings
#include <string> // for C++ strings
#include <iostream> // for output
#include <iostream> // for output
Line 458: Line 447:
std::free(msg2);
std::free(msg2);
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Clojure}}==
=={{header|Clojure}}==
{{libheader|clojure-jna}}
{{libheader|clojure-jna}}
Since Clojure is hosted on the JVM, you can follow the same approach as the [[#Java|Java]] solution and invoke your Java class from Clojure:
Since Clojure is hosted on the JVM, you can follow the same approach as the [[#Java|Java]] solution and invoke your Java class from Clojure:
<syntaxhighlight lang=clojure>(JNIDemo/callStrdup "Hello World!")</syntaxhighlight>
<syntaxhighlight lang="clojure">(JNIDemo/callStrdup "Hello World!")</syntaxhighlight>


Alternatively, to avoid having to create a library in native code you could use JNA and the clojure-jna library for convenience. Here's how you can invoke ''strcmp'' from the libc shared library:
Alternatively, to avoid having to create a library in native code you could use JNA and the clojure-jna library for convenience. Here's how you can invoke ''strcmp'' from the libc shared library:
<syntaxhighlight lang=clojure>(require '[net.n01se.clojure-jna :as jna])
<syntaxhighlight lang="clojure">(require '[net.n01se.clojure-jna :as jna])


(jna/invoke Integer c/strcmp "apple" "banana" ) ; returns -1
(jna/invoke Integer c/strcmp "apple" "banana" ) ; returns -1
Line 472: Line 460:


(jna/invoke Integer c/strcmp "banana" "banana" ) ; returns 0</syntaxhighlight>
(jna/invoke Integer c/strcmp "banana" "banana" ) ; returns 0</syntaxhighlight>

=={{header|CMake}}==
=={{header|CMake}}==
''This code uses a deprecated feature of CMake.'' In 2014, CMake 3.0 deprecated load_command(). CMake 3.0 can run this code but shows a deprecation warning. When a future version of CMake removes load_command(), this code will stop working, and there will be no way to call C functions from CMake.
''This code uses a deprecated feature of CMake.'' In 2014, CMake 3.0 deprecated load_command(). CMake 3.0 can run this code but shows a deprecation warning. When a future version of CMake removes load_command(), this code will stop working, and there will be no way to call C functions from CMake.
Line 479: Line 466:


'''CMakeLists.txt'''
'''CMakeLists.txt'''
<syntaxhighlight lang=cmake>cmake_minimum_required(VERSION 2.6)
<syntaxhighlight lang="cmake">cmake_minimum_required(VERSION 2.6)
project("outer project" C)
project("outer project" C)


Line 506: Line 493:


'''div/CMakeLists.txt'''
'''div/CMakeLists.txt'''
<syntaxhighlight lang=cmake>cmake_minimum_required(VERSION 2.6)
<syntaxhighlight lang="cmake">cmake_minimum_required(VERSION 2.6)
project(div C)
project(div C)


Line 516: Line 503:


'''div/div-command.c'''
'''div/div-command.c'''
<syntaxhighlight lang=c>#include <cmCPluginAPI.h>
<syntaxhighlight lang="c">#include <cmCPluginAPI.h>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 571: Line 558:
api = info->CAPI;
api = info->CAPI;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|COBOL}}==
=={{header|COBOL}}==
Tested with GnuCOBOL
Tested with GnuCOBOL


<syntaxhighlight lang=cobol> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. foreign.
program-id. foreign.


Line 609: Line 595:
Hello, world
Hello, world
</pre>
</pre>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


{{libheader|CFFI}}
{{libheader|CFFI}}


<syntaxhighlight lang=lisp>CL-USER> (let* ((string "Hello World!")
<syntaxhighlight lang="lisp">CL-USER> (let* ((string "Hello World!")
(c-string (cffi:foreign-funcall "strdup" :string string :pointer)))
(c-string (cffi:foreign-funcall "strdup" :string string :pointer)))
(unwind-protect (write-line (cffi:foreign-string-to-lisp c-string))
(unwind-protect (write-line (cffi:foreign-string-to-lisp c-string))
Line 621: Line 606:
Hello World!
Hello World!
; No value</syntaxhighlight>
; No value</syntaxhighlight>

=={{header|Crystal}}==
=={{header|Crystal}}==
Crystal allows to easily interface with C functions, both from object files and shared libraries.
Crystal allows to easily interface with C functions, both from object files and shared libraries.
<syntaxhighlight lang=ruby>@[Link("c")] # name of library that is passed to linker. Not needed as libc is linked by stdlib.
<syntaxhighlight lang="ruby">@[Link("c")] # name of library that is passed to linker. Not needed as libc is linked by stdlib.
lib LibC
lib LibC
fun free(ptr : Void*) : Void
fun free(ptr : Void*) : Void
Line 636: Line 620:


puts s2</syntaxhighlight>
puts s2</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>import std.stdio: writeln;
<syntaxhighlight lang="d">import std.stdio: writeln;
import std.string: toStringz;
import std.string: toStringz;
import std.conv: to;
import std.conv: to;
Line 677: Line 660:
<pre>str1: Hello World!
<pre>str1: Hello World!
str2: Hello World!</pre>
str2: Hello World!</pre>

=={{header|Delphi}}==
=={{header|Delphi}}==
===Importing the function from a shared library===
===Importing the function from a shared library===
Line 687: Line 669:
The file first has to be bound to your unit:
The file first has to be bound to your unit:


<syntaxhighlight lang=delphi>
<syntaxhighlight lang="delphi">
{$O myhello.obj}
{$O myhello.obj}
</syntaxhighlight>
</syntaxhighlight>


The next step is to do an external declaration for the function:
The next step is to do an external declaration for the function:
<syntaxhighlight lang=delphi>
<syntaxhighlight lang="delphi">
procedure Hello(S: PChar); stdcall; external;
procedure Hello(S: PChar); stdcall; external;
</syntaxhighlight>
</syntaxhighlight>


Afterwards usage of the function is just as with any other function.
Afterwards usage of the function is just as with any other function.

=={{header|Factor}}==
=={{header|Factor}}==
If you declare a parameter as <code>c-string</code>, Factor automatically converts NULL-terminated C strings to Factor strings and back. In this case we additionally have to free the returned string, so we have to do the conversion explicitly; else the reference to the pointer would be dropped behind the scenes.
If you declare a parameter as <code>c-string</code>, Factor automatically converts NULL-terminated C strings to Factor strings and back. In this case we additionally have to free the returned string, so we have to do the conversion explicitly; else the reference to the pointer would be dropped behind the scenes.


libc is already loaded, it is used by Factor elsewhere.
libc is already loaded, it is used by Factor elsewhere.
<syntaxhighlight lang=factor>FUNCTION: char* strdup ( c-string s ) ;
<syntaxhighlight lang="factor">FUNCTION: char* strdup ( c-string s ) ;


: my-strdup ( str -- str' )
: my-strdup ( str -- str' )
Line 709: Line 690:
( scratchpad ) "abc" my-strdup .
( scratchpad ) "abc" my-strdup .
"abc"
"abc"

=={{header|FBSL}}==
=={{header|FBSL}}==
Alongside its interpretative BASIC-style layer, FBSL also hosts built-in Intel-style Dynamic Assembler JIT and ANSI-C Dynamic C JIT compiler layers. BASIC, DynAsm and DynC procedures can be mixed freely to best suit the host script's intended purposes. The procedures follow their own respective syntaxes but are called in the host script in exactly the same way:
Alongside its interpretative BASIC-style layer, FBSL also hosts built-in Intel-style Dynamic Assembler JIT and ANSI-C Dynamic C JIT compiler layers. BASIC, DynAsm and DynC procedures can be mixed freely to best suit the host script's intended purposes. The procedures follow their own respective syntaxes but are called in the host script in exactly the same way:
Line 776: Line 756:


FBSL features a built-in stack balancing mechanism which eliminates stack corruption regardless of whether the API calls are using STDCALL or CDECL calling conventions. Please note that FBSL's BASIC and DynAsm '''do not''' make use of forward function declarations or header files.
FBSL features a built-in stack balancing mechanism which eliminates stack corruption regardless of whether the API calls are using STDCALL or CDECL calling conventions. Please note that FBSL's BASIC and DynAsm '''do not''' make use of forward function declarations or header files.

=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth|0.7.0}}
{{works with|GNU Forth|0.7.0}}
Line 782: Line 761:
Every version of GNU Forth has experimented with a different means to do C foreign function calls. The current implementation resolves various incompatibilities which had plagued earlier mechanisms by parsing C header files and using the host's native toolchain (i.e. gcc and ld) to generate thunks.
Every version of GNU Forth has experimented with a different means to do C foreign function calls. The current implementation resolves various incompatibilities which had plagued earlier mechanisms by parsing C header files and using the host's native toolchain (i.e. gcc and ld) to generate thunks.


<syntaxhighlight lang=forth>c-library cstrings
<syntaxhighlight lang="forth">c-library cstrings


\c #include <string.h>
\c #include <string.h>
Line 805: Line 784:


duped free throw \ gforth ALLOCATE and FREE map directly to C's malloc() and free()</syntaxhighlight>
duped free throw \ gforth ALLOCATE and FREE map directly to C's malloc() and free()</syntaxhighlight>

=={{header|Fortran}}==
=={{header|Fortran}}==
Since Fortran 2003, the standard provides the ISO_C_BINDING module to help interface with C programs. Before this, compiler vendors often provided nonstandard extensions to do this. Even with this new facility, some features, such as calling a STDCALL function on Windows, need some nonstandard extension.
Since Fortran 2003, the standard provides the ISO_C_BINDING module to help interface with C programs. Before this, compiler vendors often provided nonstandard extensions to do this. Even with this new facility, some features, such as calling a STDCALL function on Windows, need some nonstandard extension.
Line 815: Line 793:
Here is an example using the ISO_C_BINDING standard module to link against the C API functions ''strdup'', ''free'' and ''puts''. The program will print two copies of the string ''"Hello, World!"'' using the ''puts'' function. One copy is obtained from ''strdup'', then released with ''free''. The C bindings are placed in an interface module to simplify reuse. The addresses of the two copies are also printed.
Here is an example using the ISO_C_BINDING standard module to link against the C API functions ''strdup'', ''free'' and ''puts''. The program will print two copies of the string ''"Hello, World!"'' using the ''puts'' function. One copy is obtained from ''strdup'', then released with ''free''. The C bindings are placed in an interface module to simplify reuse. The addresses of the two copies are also printed.


<syntaxhighlight lang=fortran>module c_api
<syntaxhighlight lang="fortran">module c_api
use iso_c_binding
use iso_c_binding
implicit none
implicit none
Line 860: Line 838:
call free(ptr)
call free(ptr)
end program</syntaxhighlight>
end program</syntaxhighlight>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Normally it's an easy matter to call a function in the C Standard Library, statically, from FreeBASIC.
Normally it's an easy matter to call a function in the C Standard Library, statically, from FreeBASIC.
Line 866: Line 843:
As this uses LocalAlloc in kernel32.dll internally to allocate memory for the duplicated string, we need to call
As this uses LocalAlloc in kernel32.dll internally to allocate memory for the duplicated string, we need to call
LocalFree to free this memory using the pointer returned by strdup.
LocalFree to free this memory using the pointer returned by strdup.
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


'Using StrDup function in Shlwapi.dll
'Using StrDup function in Shlwapi.dll
Line 891: Line 868:
duplicate
duplicate
</pre>
</pre>

=={{header|Go}}==
=={{header|Go}}==
Using cgo, part of the standard Go command set.
Using cgo, part of the standard Go command set.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


// #include <string.h>
// #include <string.h>
Line 926: Line 902:
hello C
hello C
</pre>
</pre>

=={{header|Hare}}==
=={{header|Hare}}==
<syntaxhighlight lang=hare>// hare run -lc ffi.ha
<syntaxhighlight lang="hare">// hare run -lc ffi.ha


use fmt;
use fmt;
Line 944: Line 919:
cfree(dup);
cfree(dup);
};</syntaxhighlight>
};</syntaxhighlight>

=={{header|Haskell}}==
=={{header|Haskell}}==


<syntaxhighlight lang=Haskell>{-# LANGUAGE ForeignFunctionInterface #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE ForeignFunctionInterface #-}


import Foreign (free)
import Foreign (free)
Line 969: Line 943:
The first step is to create a shared library, to wrap the target C functions and do type conversions on the input and returned values. The arguments to the wrapper functions form a list, and this list must be unpacked to retrieve the arguments to send to the target function. To get at <code>strdup</code> and <code>strcat</code> we would have:
The first step is to create a shared library, to wrap the target C functions and do type conversions on the input and returned values. The arguments to the wrapper functions form a list, and this list must be unpacked to retrieve the arguments to send to the target function. To get at <code>strdup</code> and <code>strcat</code> we would have:


<syntaxhighlight lang=C>
<syntaxhighlight lang="c">
#include <string.h>
#include <string.h>
#include "icall.h" // a header routine from the Unicon sources - provides helpful type-conversion macros
#include "icall.h" // a header routine from the Unicon sources - provides helpful type-conversion macros
Line 992: Line 966:
Then the Unicon program must 'access' the function in the shared library: the important step is 'loadfunc' which accesses the named function in the shared library. After that, the C function can be called from within a program:
Then the Unicon program must 'access' the function in the shared library: the important step is 'loadfunc' which accesses the named function in the shared library. After that, the C function can be called from within a program:


<syntaxhighlight lang=Unicon>
<syntaxhighlight lang="unicon">
$define LIB "libstrdup-wrapper.so"
$define LIB "libstrdup-wrapper.so"


Line 1,024: Line 998:
abcdef
abcdef
</pre>
</pre>

=={{header|J}}==
=={{header|J}}==


Here is a windows specific implementation (for relatively recent versions of windows):
Here is a windows specific implementation (for relatively recent versions of windows):


<syntaxhighlight lang=J>require 'dll'
<syntaxhighlight lang="j">require 'dll'
strdup=: 'msvcrt.dll _strdup >x *' cd <
strdup=: 'msvcrt.dll _strdup >x *' cd <
free=: 'msvcrt.dll free n x' cd <
free=: 'msvcrt.dll free n x' cd <
Line 1,035: Line 1,008:


With these definitions:
With these definitions:
<syntaxhighlight lang=J> getstr@strdup 'Hello World!'
<syntaxhighlight lang="j"> getstr@strdup 'Hello World!'
Hello World!</syntaxhighlight>
Hello World!</syntaxhighlight>


Line 1,041: Line 1,014:


See also: [http://www.jsoftware.com/help/user/call_procedure.htm J's documentation]
See also: [http://www.jsoftware.com/help/user/call_procedure.htm J's documentation]

=={{header|Java}}==
=={{header|Java}}==
Java uses JNI to call other languages directly. Because it is a managed language, a "shim" layer needs to be created when dealing with things outside of the managed environment.
Java uses JNI to call other languages directly. Because it is a managed language, a "shim" layer needs to be created when dealing with things outside of the managed environment.
Line 1,048: Line 1,020:


'''JNIDemo.java'''
'''JNIDemo.java'''
<syntaxhighlight lang=java>public class JNIDemo
<syntaxhighlight lang="java">public class JNIDemo
{
{
static
static
Line 1,068: Line 1,040:


The generated file, '''JNIDemo.h''':
The generated file, '''JNIDemo.h''':
<syntaxhighlight lang=c>/* DO NOT EDIT THIS FILE - it is machine generated */
<syntaxhighlight lang="c">/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include <jni.h>
/* Header for class JNIDemo */
/* Header for class JNIDemo */
Line 1,093: Line 1,065:


'''JNIDemo.c'''
'''JNIDemo.c'''
<syntaxhighlight lang=c>#include "string.h"
<syntaxhighlight lang="c">#include "string.h"
#include "JNIDemo.h"
#include "JNIDemo.h"


Line 1,147: Line 1,119:
Hello World!
Hello World!
</pre>
</pre>

=={{header|JavaScript}}==
=={{header|JavaScript}}==
'''Node.js'''
'''Node.js'''
Line 1,155: Line 1,126:


'''md5sum.cc'''
'''md5sum.cc'''
<syntaxhighlight lang=cpp>#include <napi.h>
<syntaxhighlight lang="cpp">#include <napi.h>
#include <openssl/md5.h>
#include <openssl/md5.h>


Line 1,184: Line 1,155:
NODE_API_MODULE(addon, Init)</syntaxhighlight>
NODE_API_MODULE(addon, Init)</syntaxhighlight>
Then compile the file with [https://github.com/nodejs/node-gyp node-gyp].
Then compile the file with [https://github.com/nodejs/node-gyp node-gyp].
<syntaxhighlight lang=bash>node-gyp build</syntaxhighlight>
<syntaxhighlight lang="bash">node-gyp build</syntaxhighlight>
Once it has compiled, create the JavaScript bindings.
Once it has compiled, create the JavaScript bindings.


'''binding.js'''
'''binding.js'''
<syntaxhighlight lang=javascript>const addon = require('../build/Release/md5sum-native');
<syntaxhighlight lang="javascript">const addon = require('../build/Release/md5sum-native');


module.exports = addon.md5sum;</syntaxhighlight>
module.exports = addon.md5sum;</syntaxhighlight>
Line 1,194: Line 1,165:


''Using Require:''
''Using Require:''
<syntaxhighlight lang=javascript>const md5sum = require('../lib/binding.js');
<syntaxhighlight lang="javascript">const md5sum = require('../lib/binding.js');
console.log(md5sum('hello'));</syntaxhighlight>
console.log(md5sum('hello'));</syntaxhighlight>
{{out}}
{{out}}
Line 1,205: Line 1,176:


'''binding.js'''
'''binding.js'''
<syntaxhighlight lang=javascript>import { createRequire } from 'module';
<syntaxhighlight lang="javascript">import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const require = createRequire(import.meta.url);
const addon = require('../build/Release/md5sum-native');
const addon = require('../build/Release/md5sum-native');
Line 1,211: Line 1,182:
export default addon.md5sum;</syntaxhighlight>
export default addon.md5sum;</syntaxhighlight>
And call the function as follows:
And call the function as follows:
<syntaxhighlight lang=javascript>import md5sum from '../lib/binding.js';
<syntaxhighlight lang="javascript">import md5sum from '../lib/binding.js';


console.log(md5sum('hello'));</syntaxhighlight>
console.log(md5sum('hello'));</syntaxhighlight>
Line 1,223: Line 1,194:


Julia has a built-in keyword <code>ccall</code> to call external C-like functions. For example:
Julia has a built-in keyword <code>ccall</code> to call external C-like functions. For example:
<syntaxhighlight lang=julia>p = ccall(:strdup, Ptr{Cuchar}, (Ptr{Cuchar},), "Hello world")
<syntaxhighlight lang="julia">p = ccall(:strdup, Ptr{Cuchar}, (Ptr{Cuchar},), "Hello world")
@show unsafe_string(p) # "Hello world"
@show unsafe_string(p) # "Hello world"
ccall(:free, Void, (Ptr{Cuchar},), p)</syntaxhighlight>
ccall(:free, Void, (Ptr{Cuchar},), p)</syntaxhighlight>


'''PyCall''', [https://github.com/JuliaPy/PyCall.jl source]:
'''PyCall''', [https://github.com/JuliaPy/PyCall.jl source]:
<syntaxhighlight lang=julia>using PyCall
<syntaxhighlight lang="julia">using PyCall
@pyimport math
@pyimport math
@show math.cos(1) # 0.5403023058681398</syntaxhighlight>
@show math.cos(1) # 0.5403023058681398</syntaxhighlight>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{Works with|Ubuntu|14.04}}
{{Works with|Ubuntu|14.04}}
<syntaxhighlight lang=scala>// Kotlin Native v0.2
<syntaxhighlight lang="scala">// Kotlin Native v0.2


import kotlinx.cinterop.*
import kotlinx.cinterop.*
Line 1,248: Line 1,218:
Hello World!
Hello World!
</pre>
</pre>

=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
Use Connectivity >> Libraries & Executables >> Call Library Function Node to call an external .dll file. This example uses the WinAPI's MessageBoxA function.<br/>{{VI snippet}}<br/>
Use Connectivity >> Libraries & Executables >> Call Library Function Node to call an external .dll file. This example uses the WinAPI's MessageBoxA function.<br/>{{VI snippet}}<br/>
[[File:LabVIEW Call a foreign-language function.png]]
[[File:LabVIEW Call a foreign-language function.png]]

=={{header|Lisaac}}==
=={{header|Lisaac}}==
Use backtick notation (`...`) for referencing foreign language (C) features.
Use backtick notation (`...`) for referencing foreign language (C) features.
<syntaxhighlight lang=Lisaac>Section Header
<syntaxhighlight lang="lisaac">Section Header


+ name := TEST_C_INTERFACE;
+ name := TEST_C_INTERFACE;
Line 1,279: Line 1,247:
`free(@p)`;
`free(@p)`;
);</syntaxhighlight>
);</syntaxhighlight>

=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==
WinAPE has a built-in Z80 assembler that can copy the assembled program into the Amstrad CPC's memory. Whatever address your <code>org</code> directive was at can be <code>CALL</code>ed in BASIC.
WinAPE has a built-in Z80 assembler that can copy the assembled program into the Amstrad CPC's memory. Whatever address your <code>org</code> directive was at can be <code>CALL</code>ed in BASIC.


<syntaxhighlight lang=z80>org &1000
<syntaxhighlight lang="z80">org &1000
ld a,'A'
ld a,'A'
call &bb5a
call &bb5a
Line 1,292: Line 1,259:
A
A
Ready</pre>
Ready</pre>

=={{header|Lua}}==
=={{header|Lua}}==


Using the [http://luajit.org/ext_ffi.html FFI library] available in [http://luajit.org/ LuaJIT]:
Using the [http://luajit.org/ext_ffi.html FFI library] available in [http://luajit.org/ LuaJIT]:


<syntaxhighlight lang=lua>local ffi = require("ffi")
<syntaxhighlight lang="lua">local ffi = require("ffi")
ffi.cdef[[
ffi.cdef[[
char * strndup(const char * s, size_t n);
char * strndup(const char * s, size_t n);
Line 1,312: Line 1,278:
print("strlen: " .. ffi.C.strlen(s2))
print("strlen: " .. ffi.C.strlen(s2))
</syntaxhighlight>
</syntaxhighlight>

=={{header|Luck}}==
=={{header|Luck}}==


Luck supports interfacing with most C libraries out of the box:
Luck supports interfacing with most C libraries out of the box:


<syntaxhighlight lang=luck>import "stdio.h";;
<syntaxhighlight lang="luck">import "stdio.h";;
import "string.h";;
import "string.h";;


Line 1,324: Line 1,289:
puts(s2);;
puts(s2);;
free(s2 as void*)</syntaxhighlight>
free(s2 as void*)</syntaxhighlight>

=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
=== Call C Functions from Dll===
=== Call C Functions from Dll===
There is a difference between Windows and Wine implementation of _strdump and swprintf.
There is a difference between Windows and Wine implementation of _strdump and swprintf.
Value of '''a''' has to hold chars to read from sBuf$ as returned from msvcrt.swprintf, but this can't work in Ubuntu using Wine and in Windows as expected, so we can use '''LeftPart$(string, string as delimiter sign not included as result)'''
Value of '''a''' has to hold chars to read from sBuf$ as returned from msvcrt.swprintf, but this can't work in Ubuntu using Wine and in Windows as expected, so we can use '''LeftPart$(string, string as delimiter sign not included as result)'''
<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">


Module CheckCCall {
Module CheckCCall {
Line 1,360: Line 1,324:
===Call VbScript===
===Call VbScript===


<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Module Checkit {
Global a()
Global a()
Line 1,407: Line 1,371:


===Call Javascript===
===Call Javascript===
<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module CheckJavaScript {
Module CheckJavaScript {
Clear
Clear
Line 1,465: Line 1,429:


===Call A System Function (Win32)===
===Call A System Function (Win32)===
<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Declare MessageBox Lib "user32.MessageBoxW" {long alfa, lptext$, lpcaption$, long type}
Declare MessageBox Lib "user32.MessageBoxW" {long alfa, lptext$, lpcaption$, long type}
Print MessageBox(Hwnd, "HELLO THERE", "GEORGE", 2)
Print MessageBox(Hwnd, "HELLO THERE", "GEORGE", 2)
Line 1,473: Line 1,437:
===Make, use and remove a C Dll at runtime===
===Make, use and remove a C Dll at runtime===
H C dll to produce an array of primes. We can
H C dll to produce an array of primes. We can
<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module checkit {
Module checkit {
Static DisplayOnce=0
Static DisplayOnce=0
Line 1,600: Line 1,564:


</syntaxhighlight>
</syntaxhighlight>

=={{header|Maple}}==
=={{header|Maple}}==
We can call strdup, as requested, in the following way
We can call strdup, as requested, in the following way
<syntaxhighlight lang=Maple>> strdup := define_external( strdup, s::string, RETURN::string, LIB = "/lib/libc.so.6" ):
<syntaxhighlight lang="maple">> strdup := define_external( strdup, s::string, RETURN::string, LIB = "/lib/libc.so.6" ):
> strdup( "foo" );
> strdup( "foo" );
"foo"
"foo"
</syntaxhighlight>
</syntaxhighlight>
However, this doesn't make a lot of sense in Maple, since there can be only one copy of any Maple string in memory. Moreover, I don't see any easy way to free the memory allocated by strdup. A more sensible example for Maple follows. (It might be sensible if you wanted to compare your system library version of sin with the one built-in to Maple, for instance.)
However, this doesn't make a lot of sense in Maple, since there can be only one copy of any Maple string in memory. Moreover, I don't see any easy way to free the memory allocated by strdup. A more sensible example for Maple follows. (It might be sensible if you wanted to compare your system library version of sin with the one built-in to Maple, for instance.)
<syntaxhighlight lang=Maple>> csin := define_external( sin, s::float[8], RETURN::float[8], LIB = "libm.so" );
<syntaxhighlight lang="maple">> csin := define_external( sin, s::float[8], RETURN::float[8], LIB = "libm.so" );
csin := proc(s::numeric)
csin := proc(s::numeric)
option call_external, define_external(sin, s::float[8],
option call_external, define_external(sin, s::float[8],
Line 1,619: Line 1,582:
> csin( evalf( Pi / 2 ) );
> csin( evalf( Pi / 2 ) );
1.</syntaxhighlight>
1.</syntaxhighlight>

=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This works on windows and on linux/mac (through Mono)
This works on windows and on linux/mac (through Mono)
<syntaxhighlight lang=Mathematica>Needs["NETLink`"];
<syntaxhighlight lang="mathematica">Needs["NETLink`"];
externalstrdup = DefineDLLFunction["_strdup", "msvcrt.dll", "string", {"string"}];
externalstrdup = DefineDLLFunction["_strdup", "msvcrt.dll", "string", {"string"}];
Print["Duplicate: ", externalstrdup["Hello world!"]]</syntaxhighlight>
Print["Duplicate: ", externalstrdup["Hello world!"]]</syntaxhighlight>
Line 1,628: Line 1,590:
<pre>Duplicate: Hello world!</pre>
<pre>Duplicate: Hello world!</pre>
Also there is ExternalEvaluate that can call many other languages.
Also there is ExternalEvaluate that can call many other languages.

=={{header|Maxima}}==
=={{header|Maxima}}==
<syntaxhighlight lang=maxima>/* Maxima is written in Lisp and can call Lisp functions.
<syntaxhighlight lang="maxima">/* Maxima is written in Lisp and can call Lisp functions.
Use load("funcs.lisp"), or inside Maxima: */
Use load("funcs.lisp"), or inside Maxima: */


Line 1,639: Line 1,600:
f(5, 6);
f(5, 6);
11</syntaxhighlight>
11</syntaxhighlight>

=={{header|Mercury}}==
=={{header|Mercury}}==


Mercury is designed to interact sensibly with foreign code, even while keeping itself as pure and as safe as is possible in such circumstances. Here is an example of calling C's strdup() function from within Mercury:
Mercury is designed to interact sensibly with foreign code, even while keeping itself as pure and as safe as is possible in such circumstances. Here is an example of calling C's strdup() function from within Mercury:


<syntaxhighlight lang=mercury>:- module test_ffi.
<syntaxhighlight lang="mercury">:- module test_ffi.


:- interface.
:- interface.
Line 1,674: Line 1,634:
After this the Mercury strdup/1 function itself is declared. For purposes of exposition it has been declared fully with types and modes. The modes, however, are redundant since by default functions in Mercury have all input parameters and an output return value. Also, the determinism is declared which is again redundant. By default Mercury functions are deterministic. That line could easily have been written thusly instead:
After this the Mercury strdup/1 function itself is declared. For purposes of exposition it has been declared fully with types and modes. The modes, however, are redundant since by default functions in Mercury have all input parameters and an output return value. Also, the determinism is declared which is again redundant. By default Mercury functions are deterministic. That line could easily have been written thusly instead:


<syntaxhighlight lang=mercury>:- func strdup(string) = string.</syntaxhighlight>
<syntaxhighlight lang="mercury">:- func strdup(string) = string.</syntaxhighlight>


The next block of code is the foreign_proc pragma declaration. In this declaration the language ("C") is declared, the footprint of the function is again provided, this time with variable names and modes but without the determinism, a set of properties is declared and the actual C code to be executed is provided. This last piece is trivial, but the properties themselves are worth looking more closely at.
The next block of code is the foreign_proc pragma declaration. In this declaration the language ("C") is declared, the footprint of the function is again provided, this time with variable names and modes but without the determinism, a set of properties is declared and the actual C code to be executed is provided. This last piece is trivial, but the properties themselves are worth looking more closely at.
Line 1,681: Line 1,641:


Of note is that '''no separate C source file needs to be provided'''. The compiler takes care of putting in all the required boilerplate code necessary to conform to the specifications provided. The resulting code can be treated as much a part of the program as any native Mercury code would be: types, modes, determinism, purity, etc. all managed similarly.
Of note is that '''no separate C source file needs to be provided'''. The compiler takes care of putting in all the required boilerplate code necessary to conform to the specifications provided. The resulting code can be treated as much a part of the program as any native Mercury code would be: types, modes, determinism, purity, etc. all managed similarly.

=={{header|Modula-2}}==
=={{header|Modula-2}}==
The first file (Vga.c) creates the function prototypes.
The first file (Vga.c) creates the function prototypes.
<syntaxhighlight lang=c>#include <vga.h>
<syntaxhighlight lang="c">#include <vga.h>


int Initialize (void)
int Initialize (void)
Line 1,753: Line 1,712:
}</syntaxhighlight>
}</syntaxhighlight>
The next file is the definition module, but in this context it is called a '''FOREIGN MODULE'''.
The next file is the definition module, but in this context it is called a '''FOREIGN MODULE'''.
<syntaxhighlight lang=modula2>FOREIGN MODULE Vga;
<syntaxhighlight lang="modula2">FOREIGN MODULE Vga;


TYPE EGAcolour = (black, blue, green, cyan, red, pink, brown, white,
TYPE EGAcolour = (black, blue, green, cyan, red, pink, brown, white,
Line 1,786: Line 1,745:
END Vga.</syntaxhighlight>
END Vga.</syntaxhighlight>
The third file is an example program.
The third file is an example program.
<syntaxhighlight lang=modula2>MODULE svg01;
<syntaxhighlight lang="modula2">MODULE svg01;


FROM InOut IMPORT Read, Write, WriteBf, WriteString;
FROM InOut IMPORT Read, Write, WriteBf, WriteString;
Line 1,819: Line 1,778:
WriteBf;
WriteBf;
END svg01.</syntaxhighlight>
END svg01.</syntaxhighlight>

=={{header|Modula-3}}==
=={{header|Modula-3}}==
Modula-3 provides many predefined interfaces to C files. Here we use <tt>Cstring</tt> which uses C string functions. Note we have to convert strings of type <tt>TEXT</tt> into C strings (NULL terminated character arrays). Also note the code requires the <tt>UNSAFE</tt> keyword because it interfaces with C (which is unsafe).
Modula-3 provides many predefined interfaces to C files. Here we use <tt>Cstring</tt> which uses C string functions. Note we have to convert strings of type <tt>TEXT</tt> into C strings (NULL terminated character arrays). Also note the code requires the <tt>UNSAFE</tt> keyword because it interfaces with C (which is unsafe).
<syntaxhighlight lang=modula3>UNSAFE MODULE Foreign EXPORTS Main;
<syntaxhighlight lang="modula3">UNSAFE MODULE Foreign EXPORTS Main;


IMPORT IO, Ctypes, Cstring, M3toC;
IMPORT IO, Ctypes, Cstring, M3toC;
Line 1,843: Line 1,801:
string1 # string2
string1 # string2
</pre>
</pre>

=={{header|Mosaic}}==
=={{header|Mosaic}}==
<syntaxhighlight lang=mosaic>import clib
<syntaxhighlight lang="mosaic">import clib


importdll msvcrt =
importdll msvcrt =
Line 1,857: Line 1,814:
println str2
println str2
end</syntaxhighlight>
end</syntaxhighlight>

=={{header|Never}}==
=={{header|Never}}==
Never includes libffi for access to foreign functions, but currently only supports very basic types, int, float, string. ''strdup'' will work, but the ''voidness'' of ''free'' is not yet supported. This solution uses some of the Math functions in libm instead.
Never includes libffi for access to foreign functions, but currently only supports very basic types, int, float, string. ''strdup'' will work, but the ''voidness'' of ''free'' is not yet supported. This solution uses some of the Math functions in libm instead.


<syntaxhighlight lang=fsharp>extern "libm.so.6" func sinhf(x : float) -> float
<syntaxhighlight lang="fsharp">extern "libm.so.6" func sinhf(x : float) -> float
extern "libm.so.6" func coshf(x : float) -> float
extern "libm.so.6" func coshf(x : float) -> float
extern "libm.so.6" func powf(base : float, exp : float) -> float
extern "libm.so.6" func powf(base : float, exp : float) -> float
Line 1,891: Line 1,847:
1.18
1.18
</pre>
</pre>

=={{header|NewLISP}}==
=={{header|NewLISP}}==
newLISP has two FFI APIs. The simple API needs no type specifiers but is limited to integers and pointers.
newLISP has two FFI APIs. The simple API needs no type specifiers but is limited to integers and pointers.
The extended API can specify types for return values and parameters and can also be used for floats and structs.
The extended API can specify types for return values and parameters and can also be used for floats and structs.
<syntaxhighlight lang=NewLISP>; simple FFI interface on Mac OSX
<syntaxhighlight lang="newlisp">; simple FFI interface on Mac OSX
(import "libc.dylib" "strdup")
(import "libc.dylib" "strdup")
(println (get-string (strdup "hello world")))
(println (get-string (strdup "hello world")))
Line 1,903: Line 1,858:
(println (strdup "hello world"))
(println (strdup "hello world"))
</syntaxhighlight>
</syntaxhighlight>

=={{header|Nim}}==
=={{header|Nim}}==
Since Nim compiles to C by default, this task is easily done:
Since Nim compiles to C by default, this task is easily done:


<syntaxhighlight lang=nim>proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
<syntaxhighlight lang="nim">proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
echo strcmp("abc", "def")
echo strcmp("abc", "def")
echo strcmp("hello", "hello")
echo strcmp("hello", "hello")
Line 1,915: Line 1,869:
var x = "foo"
var x = "foo"
printf("Hello %d %s!\n", 12, x)</syntaxhighlight>
printf("Hello %d %s!\n", 12, x)</syntaxhighlight>

=={{header|OCaml}}==
=={{header|OCaml}}==


===Outline of what is linked against===
===Outline of what is linked against===
For the hypothetical [[C]] library that contains functions described by a header file with this in:
For the hypothetical [[C]] library that contains functions described by a header file with this in:
<syntaxhighlight lang=ocaml>void myfunc_a();
<syntaxhighlight lang="ocaml">void myfunc_a();
float myfunc_b(int, float);
float myfunc_b(int, float);
char *myfunc_c(int *, int);</syntaxhighlight>
char *myfunc_c(int *, int);</syntaxhighlight>
Line 1,929: Line 1,882:


====file "mylib.ml":====
====file "mylib.ml":====
<syntaxhighlight lang=ocaml>external myfunc_a: unit -> unit = "caml_myfunc_a"
<syntaxhighlight lang="ocaml">external myfunc_a: unit -> unit = "caml_myfunc_a"
external myfunc_b: int -> float -> float = "caml_myfunc_b"
external myfunc_b: int -> float -> float = "caml_myfunc_b"
external myfunc_c: int array -> string = "caml_myfunc_c"</syntaxhighlight>
external myfunc_c: int array -> string = "caml_myfunc_c"</syntaxhighlight>


====file "wrap_mylib.c":====
====file "wrap_mylib.c":====
<syntaxhighlight lang=c>#include <caml/mlvalues.h>
<syntaxhighlight lang="c">#include <caml/mlvalues.h>
#include <caml/alloc.h>
#include <caml/alloc.h>
#include <mylib.h>
#include <mylib.h>
Line 1,967: Line 1,920:
====the Makefile:====
====the Makefile:====
(replace spaces by tabs)
(replace spaces by tabs)
<syntaxhighlight lang=makefile>wrap_mylib.o: wrap_mylib.c
<syntaxhighlight lang="makefile">wrap_mylib.o: wrap_mylib.c
ocamlc -c -ccopt -I/usr/include/mylib $<
ocamlc -c -ccopt -I/usr/include/mylib $<


Line 2,001: Line 1,954:
There is another solution for calling C functions from a C library which is to use '''ocaml-ctypes'''. We can then define bindings by writing only OCaml code without any C stubs. The equivalent for wrapping the previous hypothetical [[C]] library will be:
There is another solution for calling C functions from a C library which is to use '''ocaml-ctypes'''. We can then define bindings by writing only OCaml code without any C stubs. The equivalent for wrapping the previous hypothetical [[C]] library will be:


<syntaxhighlight lang=ocaml>open Ctypes
<syntaxhighlight lang="ocaml">open Ctypes
open Foreign
open Foreign


Line 2,012: Line 1,965:
myfunc_c (to_voidp (CArray.start arr)) (CArray.length arr)
myfunc_c (to_voidp (CArray.start arr)) (CArray.length arr)
;;</syntaxhighlight>
;;</syntaxhighlight>

=={{header|Ol}}==
=={{header|Ol}}==
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(import (otus ffi))
(import (otus ffi))


Line 2,024: Line 1,976:


Windows has no a "strdup" function, so windows version should look like this.
Windows has no a "strdup" function, so windows version should look like this.
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(import (otus ffi))
(import (otus ffi))


Line 2,039: Line 1,991:


Ol provides a way to call ol functions directly from native code (means callbacks).
Ol provides a way to call ol functions directly from native code (means callbacks).
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
; The sample usage of GTK3+ library
; The sample usage of GTK3+ library
(import (otus ffi)
(import (otus ffi)
Line 2,075: Line 2,027:
(g_application_run app 0 #false)
(g_application_run app 0 #false)
</syntaxhighlight>
</syntaxhighlight>

=={{header|Oz}}==
=={{header|Oz}}==
First we need to create a so-called "native functor" that converts the arguments and describes the C functions:
First we need to create a so-called "native functor" that converts the arguments and describes the C functions:
<syntaxhighlight lang=cpp>#include "mozart.h"
<syntaxhighlight lang="cpp">#include "mozart.h"
#include <string.h>
#include <string.h>


Line 2,101: Line 2,052:


Save this file as "strdup.cc". To automate compiling and linking, we need a makefile for <code>ozmake</code>, the Oz build tool. Save this file as "makefile.oz":
Save this file as "strdup.cc". To automate compiling and linking, we need a makefile for <code>ozmake</code>, the Oz build tool. Save this file as "makefile.oz":
<syntaxhighlight lang=oz>makefile(
<syntaxhighlight lang="oz">makefile(
lib : [
lib : [
'strdup.o' 'strdup.so'
'strdup.o' 'strdup.so'
Line 2,111: Line 2,062:
Now we can write some code that uses the wrapped C function (make sure Emacs' working directory is set to the same directory):
Now we can write some code that uses the wrapped C function (make sure Emacs' working directory is set to the same directory):


<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
[Strdup] = {Module.link ['strdup.so{native}']}
[Strdup] = {Module.link ['strdup.so{native}']}
in
in
{System.showInfo {Strdup.strdup "hello"}}</syntaxhighlight>
{System.showInfo {Strdup.strdup "hello"}}</syntaxhighlight>

=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Of course it is trivial to include C functions in PARI, and not uncommon. C++ functions are similar, as PARI is written in a C++-friendly style. The <code>system</code> and <code>install</code> commands allow foreign-language functions to be called from within gp.
Of course it is trivial to include C functions in PARI, and not uncommon. C++ functions are similar, as PARI is written in a C++-friendly style. The <code>system</code> and <code>install</code> commands allow foreign-language functions to be called from within gp.

=={{header|Pascal}}==
=={{header|Pascal}}==
See [[Call_a_foreign-language_function#Delphi | Delphi]]
See [[Call_a_foreign-language_function#Delphi | Delphi]]

=={{header|Perl}}==
=={{header|Perl}}==
Perl code calls a C function <code>c_dup()</code> passing a string <code>'Hello'</code> as an argument, which gets transparently converted to a C string, the <code>c_dup()</code> function makes a copy of that string using <code>strdup()</code> function, stores pointer to the copy in the <code>copy</code> variable and returns it. The returned <code>char</code> pointer gets converted transparently to a Perl string value and gets returned to the calling Perl code which prints it. Then the Perl code calls a C function <code>c_free()</code> to free the allocated memory. Both of the C functions are defined inline in the Perl program and are automatically compiled (only once, unless they change) and linked at runtime. Here is the entire program:
Perl code calls a C function <code>c_dup()</code> passing a string <code>'Hello'</code> as an argument, which gets transparently converted to a C string, the <code>c_dup()</code> function makes a copy of that string using <code>strdup()</code> function, stores pointer to the copy in the <code>copy</code> variable and returns it. The returned <code>char</code> pointer gets converted transparently to a Perl string value and gets returned to the calling Perl code which prints it. Then the Perl code calls a C function <code>c_free()</code> to free the allocated memory. Both of the C functions are defined inline in the Perl program and are automatically compiled (only once, unless they change) and linked at runtime. Here is the entire program:
<syntaxhighlight lang=perl>use Inline C => q{
<syntaxhighlight lang="perl">use Inline C => q{
char *copy;
char *copy;
char * c_dup(char *orig) {
char * c_dup(char *orig) {
Line 2,137: Line 2,085:


Another example, instead of returning the copy to Perl code it prints it using C printf:
Another example, instead of returning the copy to Perl code it prints it using C printf:
<syntaxhighlight lang=perl>use Inline C => q{
<syntaxhighlight lang="perl">use Inline C => q{
void c_hello (char *text) {
void c_hello (char *text) {
char *copy = strdup(text);
char *copy = strdup(text);
Line 2,145: Line 2,093:
};
};
c_hello 'world';</syntaxhighlight>
c_hello 'world';</syntaxhighlight>

=={{header|Phix}}==
=={{header|Phix}}==
The foreign language functions must be compiled to .dll (or .so) form.<br>
The foreign language functions must be compiled to .dll (or .so) form.<br>
Line 2,151: Line 2,098:
a library component which can be re-used in different applications.<br>
a library component which can be re-used in different applications.<br>
See also builtins/cffi.e, a text-based C interface that handles C-style structs, unions, and function declarations directly.
See also builtins/cffi.e, a text-based C interface that handles C-style structs, unions, and function declarations directly.
<!--<syntaxhighlight lang=Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- not from a browser, mate!</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- not from a browser, mate!</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">shlwapi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">open_dll</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"shlwapi.dll"</span><span style="color: #0000FF;">),</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">shlwapi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">open_dll</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"shlwapi.dll"</span><span style="color: #0000FF;">),</span>
Line 2,167: Line 2,114:
"Hello World!"
"Hello World!"
</pre>
</pre>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
The easiest is to inline the C code. Another possibility would be to write it
The easiest is to inline the C code. Another possibility would be to write it
Line 2,177: Line 2,123:


===32-bit version===
===32-bit version===
<syntaxhighlight lang=PicoLisp>(load "@lib/gcc.l")
<syntaxhighlight lang="picolisp">(load "@lib/gcc.l")


(gcc "str" NIL # The 'gcc' function passes all text
(gcc "str" NIL # The 'gcc' function passes all text
Line 2,197: Line 2,143:
(println 'Duplicate (duptest "Hello world!"))</syntaxhighlight>
(println 'Duplicate (duptest "Hello world!"))</syntaxhighlight>
===64-bit version===
===64-bit version===
<syntaxhighlight lang=C>
<syntaxhighlight lang="c">
/*
/*
How to create the shared lib/so file:
How to create the shared lib/so file:
Line 2,220: Line 2,166:
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang=PicoLisp>
<syntaxhighlight lang="picolisp">
(prinl "Calling custom so/dll library...")
(prinl "Calling custom so/dll library...")
(set 'A NIL)
(set 'A NIL)
Line 2,235: Line 2,181:
</pre>
</pre>
</out>
</out>

=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=text>declare strdup entry (character (30) varyingz) options (fastcall16);
<syntaxhighlight lang="text">declare strdup entry (character (30) varyingz) options (fastcall16);


put (strdup('hello world') );</syntaxhighlight>
put (strdup('hello world') );</syntaxhighlight>

=={{header|Prolog}}==
=={{header|Prolog}}==
In SWI-Prolog we need to do two things. First we need to declare a mapping from a Prolog file to a C implementation:
In SWI-Prolog we need to do two things. First we need to declare a mapping from a Prolog file to a C implementation:


<syntaxhighlight lang=prolog>:- module(plffi, [strdup/2]).
<syntaxhighlight lang="prolog">:- module(plffi, [strdup/2]).
:- use_foreign_library(plffi).</syntaxhighlight>
:- use_foreign_library(plffi).</syntaxhighlight>


Line 2,251: Line 2,195:
Then we need to write a C file that gives us the interface to the underlying C function (strdup in this case), mapping the ''predicate''' call to a C '''function''' call:
Then we need to write a C file that gives us the interface to the underlying C function (strdup in this case), mapping the ''predicate''' call to a C '''function''' call:


<syntaxhighlight lang=c>#include <string.h>
<syntaxhighlight lang="c">#include <string.h>
#include <stdio.h>
#include <stdio.h>
#include <SWI-Prolog.h>
#include <SWI-Prolog.h>
Line 2,278: Line 2,222:
We compile this very easily:
We compile this very easily:


<syntaxhighlight lang=sh>$ swipl-ld -o plffi -shared plffi.c</syntaxhighlight>
<syntaxhighlight lang="sh">$ swipl-ld -o plffi -shared plffi.c</syntaxhighlight>


Then, from within the SWI-Prolog interactor:
Then, from within the SWI-Prolog interactor:


<syntaxhighlight lang=Prolog>?- [plffi].
<syntaxhighlight lang="prolog">?- [plffi].
% plffi compiled into plffi 0.04 sec, 1,477 clauses
% plffi compiled into plffi 0.04 sec, 1,477 clauses
true.
true.
Line 2,297: Line 2,241:
?- X = booger, strdup(booger, X).
?- X = booger, strdup(booger, X).
X = booger.</syntaxhighlight>
X = booger.</syntaxhighlight>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
Here we will use [http://flatassembler.net/ Fasm (flat assembler)] to create an object file and then import the function
Here we will use [http://flatassembler.net/ Fasm (flat assembler)] to create an object file and then import the function
Line 2,303: Line 2,246:
the resulting executable. [http://www.purebasic.com/ PureBasic] supports {Windows, Linux, MacOS}.
the resulting executable. [http://www.purebasic.com/ PureBasic] supports {Windows, Linux, MacOS}.


<syntaxhighlight lang=PureBasic>
<syntaxhighlight lang="purebasic">
; Call_a_foreign_language_function.fasm -> Call_a_foreign_language_function.obj
; Call_a_foreign_language_function.fasm -> Call_a_foreign_language_function.obj
; the assembler code...
; the assembler code...
Line 2,345: Line 2,288:
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang=PureBasic>
<syntaxhighlight lang="purebasic">
; the PureBasic code...
; the PureBasic code...


Line 2,363: Line 2,306:
HELLO WORLD!!
HELLO WORLD!!
</pre>
</pre>

=={{header|Python}}==
=={{header|Python}}==


<syntaxhighlight lang=python>import ctypes
<syntaxhighlight lang="python">import ctypes
libc = ctypes.CDLL("/lib/libc.so.6")
libc = ctypes.CDLL("/lib/libc.so.6")
libc.strcmp("abc", "def") # -1
libc.strcmp("abc", "def") # -1
libc.strcmp("hello", "hello") # 0</syntaxhighlight>
libc.strcmp("hello", "hello") # 0</syntaxhighlight>

=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket/base
#lang racket/base
(require ffi/unsafe)
(require ffi/unsafe)
Line 2,415: Line 2,356:
(strdup "Hello World!")
(strdup "Hello World!")
</syntaxhighlight>
</syntaxhighlight>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{Works with|rakudo|2016.07}}
{{Works with|rakudo|2016.07}}
<syntaxhighlight lang=raku line>use NativeCall;
<syntaxhighlight lang="raku" line>use NativeCall;


sub strdup(Str $s --> Pointer) is native {*}
sub strdup(Str $s --> Pointer) is native {*}
Line 2,432: Line 2,372:
puts returns 9
puts returns 9
free returns 0</pre>
free returns 0</pre>

=={{header|REALbasic}}==
=={{header|REALbasic}}==
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _
CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer
CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer
Line 2,458: Line 2,397:
End If
End If
</syntaxhighlight>
</syntaxhighlight>

=={{header|REXX}}==
=={{header|REXX}}==
The use of the &nbsp; '''address''' &nbsp; statement isn't normally required, but it's shown here as an illustrative example.
The use of the &nbsp; '''address''' &nbsp; statement isn't normally required, but it's shown here as an illustrative example.
<syntaxhighlight lang=rexx>/*REXX program calls (invoke) a "foreign" (non-REXX) language routine/program. */
<syntaxhighlight lang="rexx">/*REXX program calls (invoke) a "foreign" (non-REXX) language routine/program. */


cmd = "MODE" /*define the command that is to be used*/
cmd = "MODE" /*define the command that is to be used*/
Line 2,475: Line 2,413:
Code page: 437
Code page: 437
</pre>
</pre>

=={{header|Ruby}}==
=={{header|Ruby}}==


Line 2,487: Line 2,424:


{{works with|MRI}}
{{works with|MRI}}
<syntaxhighlight lang=c>/* rc_strdup.c */
<syntaxhighlight lang="c">/* rc_strdup.c */
#include <stdlib.h> /* free() */
#include <stdlib.h> /* free() */
#include <string.h> /* strdup() */
#include <string.h> /* strdup() */
Line 2,522: Line 2,459:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=ruby># extconf.rb
<syntaxhighlight lang="ruby"># extconf.rb
require 'mkmf'
require 'mkmf'
create_makefile('rc_strdup')</syntaxhighlight>
create_makefile('rc_strdup')</syntaxhighlight>


<syntaxhighlight lang=ruby># demo.rb
<syntaxhighlight lang="ruby"># demo.rb
require 'rc_strdup'
require 'rc_strdup'
puts RosettaCode.strdup('This string gets duplicated.')</syntaxhighlight>
puts RosettaCode.strdup('This string gets duplicated.')</syntaxhighlight>
Line 2,534: Line 2,471:
A recent effort to make it easier to write libraries, portable across platforms and interpreters, led to the creation of a [http://sourceware.org/libffi/ libffi] binding simply called [http://wiki.github.com/ffi/ffi/ ffi] for completely dynamic calls.
A recent effort to make it easier to write libraries, portable across platforms and interpreters, led to the creation of a [http://sourceware.org/libffi/ libffi] binding simply called [http://wiki.github.com/ffi/ffi/ ffi] for completely dynamic calls.


<syntaxhighlight lang=ruby>
<syntaxhighlight lang="ruby">
require 'ffi'
require 'ffi'


Line 2,557: Line 2,494:


{{works with|Ruby|2.0+}}
{{works with|Ruby|2.0+}}
<syntaxhighlight lang=ruby>require 'fiddle'
<syntaxhighlight lang="ruby">require 'fiddle'


# Find strdup(). It takes a pointer and returns a pointer.
# Find strdup(). It takes a pointer and returns a pointer.
Line 2,574: Line 2,511:


{{works with|Ruby|2.0+}}
{{works with|Ruby|2.0+}}
<syntaxhighlight lang=ruby>require 'fiddle'
<syntaxhighlight lang="ruby">require 'fiddle'
require 'fiddle/import'
require 'fiddle/import'


Line 2,591: Line 2,528:
Using {{libheader|RubyGems}} package [http://www.zenspider.com/ZSS/Products/RubyInline/ RubyInline], which compiles the inlined code on demand during runtime.
Using {{libheader|RubyGems}} package [http://www.zenspider.com/ZSS/Products/RubyInline/ RubyInline], which compiles the inlined code on demand during runtime.


<syntaxhighlight lang=ruby>require 'rubygems'
<syntaxhighlight lang="ruby">require 'rubygems'
require 'inline'
require 'inline'


Line 2,631: Line 2,568:
[14, 87178291200, 1278945280]
[14, 87178291200, 1278945280]
9</pre>
9</pre>

=={{header|Rust}}==
=={{header|Rust}}==


<syntaxhighlight lang=rust>extern crate libc;
<syntaxhighlight lang="rust">extern crate libc;


//c function that returns the sum of two integers
//c function that returns the sum of two integers
Line 2,647: Line 2,583:
assert!( (output == (in1 + in2) ),"Error in sum calculation") ;
assert!( (output == (in1 + in2) ),"Error in sum calculation") ;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==
<syntaxhighlight lang=Scala>object JNIDemo {
<syntaxhighlight lang="scala">object JNIDemo {
try System.loadLibrary("JNIDemo")
try System.loadLibrary("JNIDemo")


Line 2,660: Line 2,595:


{{works with | Smalltalk/X}}
{{works with | Smalltalk/X}}
<syntaxhighlight lang=Smalltalk>Object subclass:'CallDemo'!
<syntaxhighlight lang="smalltalk">Object subclass:'CallDemo'!
!CallDemo class methods!
!CallDemo class methods!
strdup:arg
strdup:arg
Line 2,667: Line 2,602:


Transcript showCR:( CallDemo strdup:'Hello' )</syntaxhighlight>
Transcript showCR:( CallDemo strdup:'Hello' )</syntaxhighlight>

=={{header|Stata}}==
=={{header|Stata}}==
Here are examples showing how to build and call from Stata a plugin written in C or Java. See also the entries 29 to 32 in the ''[https://blog.stata.com/2016/01/15/programming-an-estimation-command-in-stata-a-map-to-posted-entries/ Programming an estimation command in Stata]'' series by David M. Drukker, on [https://blog.stata.com/ Stata Blog].
Here are examples showing how to build and call from Stata a plugin written in C or Java. See also the entries 29 to 32 in the ''[https://blog.stata.com/2016/01/15/programming-an-estimation-command-in-stata-a-map-to-posted-entries/ Programming an estimation command in Stata]'' series by David M. Drukker, on [https://blog.stata.com/ Stata Blog].
Line 2,676: Line 2,610:
As an example let's build a '''[https://en.wikipedia.org/wiki/Hilbert_matrix Hilbert matrix]''' in C.
As an example let's build a '''[https://en.wikipedia.org/wiki/Hilbert_matrix Hilbert matrix]''' in C.


<syntaxhighlight lang=c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include "stplugin.h"
#include "stplugin.h"


Line 2,695: Line 2,629:
Declare also an ADO file to call the plugin:
Declare also an ADO file to call the plugin:


<syntaxhighlight lang=stata>program hilbert
<syntaxhighlight lang="stata">program hilbert
matrix define `1'=J(`2',`2',0)
matrix define `1'=J(`2',`2',0)
plugin call hilbertmat, `1' `2'
plugin call hilbertmat, `1' `2'
Line 2,704: Line 2,638:
Then, you may call
Then, you may call


<syntaxhighlight lang=stata>. hilbert mymat 4
<syntaxhighlight lang="stata">. hilbert mymat 4


. matrix list mymat
. matrix list mymat
Line 2,722: Line 2,656:
As an example let's build a '''[https://en.wikipedia.org/wiki/Hilbert_matrix Hilbert matrix]''' in Java.
As an example let's build a '''[https://en.wikipedia.org/wiki/Hilbert_matrix Hilbert matrix]''' in Java.


<syntaxhighlight lang=java>import com.stata.sfi.*;
<syntaxhighlight lang="java">import com.stata.sfi.*;


public class HilbertMatrix {
public class HilbertMatrix {
Line 2,743: Line 2,677:
In Stata, assuming HilbertMatrix.class resides in K:\java:
In Stata, assuming HilbertMatrix.class resides in K:\java:


<syntaxhighlight lang=stata>. javacall HilbertMatrix run, classpath(K:\java) args(mymat 4)
<syntaxhighlight lang="stata">. javacall HilbertMatrix run, classpath(K:\java) args(mymat 4)


. matrix list mymat
. matrix list mymat
Line 2,756: Line 2,690:
Notice that Mata has the builtin function '''[https://www.stata.com/help.cgi?mf_Hilbert Hilbert]''' to do the same:
Notice that Mata has the builtin function '''[https://www.stata.com/help.cgi?mf_Hilbert Hilbert]''' to do the same:


<syntaxhighlight lang=stata>. mata: Hilbert(4)
<syntaxhighlight lang="stata">. mata: Hilbert(4)
[symmetric]
[symmetric]
1 2 3 4
1 2 3 4
Line 2,765: Line 2,699:
4 | .25 .2 .1666666667 .1428571429 |
4 | .25 .2 .1666666667 .1428571429 |
+---------------------------------------------------------+</syntaxhighlight>
+---------------------------------------------------------+</syntaxhighlight>

=={{header|Swift}}==
=={{header|Swift}}==
Because Swift uses the Objective-C runtime it is trivial to call C/Objective-C functions directly in Swift.
Because Swift uses the Objective-C runtime it is trivial to call C/Objective-C functions directly in Swift.
<syntaxhighlight lang=Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


let hello = "Hello, World!"
let hello = "Hello, World!"
let fromC = strdup(hello)
let fromC = strdup(hello)
let backToSwiftString = String.fromCString(fromC)</syntaxhighlight>
let backToSwiftString = String.fromCString(fromC)</syntaxhighlight>

=={{header|Tcl}}==
=={{header|Tcl}}==
{{libheader|critcl}}
{{libheader|critcl}}
In this solution, we wrap up the <code>ilogb</code> function from C's math library with critcl so that it becomes one of Tcl's normal functions (assuming Tcl 8.5):
In this solution, we wrap up the <code>ilogb</code> function from C's math library with critcl so that it becomes one of Tcl's normal functions (assuming Tcl 8.5):
<syntaxhighlight lang=tcl>package require critcl
<syntaxhighlight lang="tcl">package require critcl
critcl::code {
critcl::code {
#include <math.h>
#include <math.h>
Line 2,787: Line 2,719:
Note that we do not show <code>strdup</code> here because Tcl manages the memory for strings in complex ways and does not guarantee to preserve string pointers from one call into the C API to the next (e.g., if it has to apply an encoding transformation behind the scenes).
Note that we do not show <code>strdup</code> here because Tcl manages the memory for strings in complex ways and does not guarantee to preserve string pointers from one call into the C API to the next (e.g., if it has to apply an encoding transformation behind the scenes).
<!-- TODO: a basic thunk, and show off using SWIG -->
<!-- TODO: a basic thunk, and show off using SWIG -->

=={{header|TXR}}==
=={{header|TXR}}==


Line 2,803: Line 2,734:


There is no way to use the <code>str</code> family of types, yet do manual memory management; FFI manages automatically. Code that wants to manually manage a foreign resource referenced by pointer should use <code>cptr</code> or <code>carray</code>, depending on required semantics.
There is no way to use the <code>str</code> family of types, yet do manual memory management; FFI manages automatically. Code that wants to manually manage a foreign resource referenced by pointer should use <code>cptr</code> or <code>carray</code>, depending on required semantics.

=={{header|Wren}}==
=={{header|Wren}}==
Although RC task solutions are usually written for execution by Wren CLI, the language's main purpose is for embedding and the embedding API is written in C. It is therefore a relative easy matter to call a C function from Wren after first embedding the latter in a suitable C program.
Although RC task solutions are usually written for execution by Wren CLI, the language's main purpose is for embedding and the embedding API is written in C. It is therefore a relative easy matter to call a C function from Wren after first embedding the latter in a suitable C program.


<syntaxhighlight lang=ecmascript>/* call_foreign_language_function.wren */
<syntaxhighlight lang="ecmascript">/* call_foreign_language_function.wren */


class C {
class C {
Line 2,819: Line 2,749:


Note that it's safe to free the pointer returned by strdup after passing it to Wren because wrenSetSlotString copies the C string to a new String object managed by Wren’s garbage collector.
Note that it's safe to free the pointer returned by strdup after passing it to Wren because wrenSetSlotString copies the C string to a new String object managed by Wren’s garbage collector.
<syntaxhighlight lang=C>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
Line 2,907: Line 2,837:
Hello World!
Hello World!
</pre>
</pre>

=={{header|X86-64 Assembly}}==
=={{header|X86-64 Assembly}}==
===UASM 2.52===
===UASM 2.52===
Calling C functions in Assembly is trivial at best. It's not anymore complicated than using them in C itself. Strdup for example..
Calling C functions in Assembly is trivial at best. It's not anymore complicated than using them in C itself. Strdup for example..
<syntaxhighlight lang=asm>
<syntaxhighlight lang="asm">
option casemap:none
option casemap:none


Line 2,945: Line 2,874:
====Lua====
====Lua====
Using the liblua that comes with Lua 5.2(?). Assembling is the same as always, Link with a -llua using clang or gcc.
Using the liblua that comes with Lua 5.2(?). Assembling is the same as always, Link with a -llua using clang or gcc.
<syntaxhighlight lang=asm>
<syntaxhighlight lang="asm">
option casemap:none
option casemap:none


Line 3,194: Line 3,123:
</syntaxhighlight>
</syntaxhighlight>
Addition.lua
Addition.lua
<syntaxhighlight lang=lua>
<syntaxhighlight lang="lua">
function addition(a, b)
function addition(a, b)
print('---> Lua calc: ' .. a .. ' + ' .. b .. ' = ' .. a+b)
print('---> Lua calc: ' .. a .. ' + ' .. b .. ' = ' .. a+b)
Line 3,214: Line 3,143:
{{trans|Wren}}
{{trans|Wren}}
So yeah. This inits Wrens VM in Assembly to call strdup in C. Now PIE(Position independent executable) compliant.
So yeah. This inits Wrens VM in Assembly to call strdup in C. Now PIE(Position independent executable) compliant.
<syntaxhighlight lang=asm>
<syntaxhighlight lang="asm">
;; libc stuff..
;; libc stuff..
extern printf
extern printf
Line 3,394: Line 3,323:
</syntaxhighlight>
</syntaxhighlight>
strdup.wren
strdup.wren
<syntaxhighlight lang=wren>
<syntaxhighlight lang="wren">
class C {
class C {
foreign static strdup(s)
foreign static strdup(s)
Line 3,402: Line 3,331:
</syntaxhighlight>
</syntaxhighlight>
strdup.c
strdup.c
<syntaxhighlight lang=c>
<syntaxhighlight lang="c">
void free( void* ptr );
void free( void* ptr );
char * strdup( const char *str1 );
char * strdup( const char *str1 );
Line 3,422: Line 3,351:
Goodbye, World!
Goodbye, World!
</pre>
</pre>

=={{header|Zig}}==
=={{header|Zig}}==
<syntaxhighlight lang=zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
const c = @cImport({
const c = @cImport({
@cInclude("stdlib.h"); // `free`
@cInclude("stdlib.h"); // `free`
Line 3,437: Line 3,365:
c.free(copy);
c.free(copy);
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|zkl}}==
=={{header|zkl}}==
In my opinion, FFIs are very problematic and it is better, if you really need external functionality, to spend the effort to write a glue library. Certainly a lot more work. And it only works for C or C++.
In my opinion, FFIs are very problematic and it is better, if you really need external functionality, to spend the effort to write a glue library. Certainly a lot more work. And it only works for C or C++.
Line 3,444: Line 3,371:


flf.c:
flf.c:
<syntaxhighlight lang=c>//-*-c-*-
<syntaxhighlight lang="c">//-*-c-*-
// flf.c, Call a foreign-language function
// flf.c, Call a foreign-language function


Line 3,494: Line 3,421:
3
3
</pre>
</pre>

{{omit from|360 Assembly|A CPU only understands its own machine language. So no assembly language can do this.}}
{{omit from|360 Assembly|A CPU only understands its own machine language. So no assembly language can do this.}}
{{omit from|6502 Assembly}}
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|8051 Assembly}}
{{omit from|8051 Assembly}}
{{omit from|8080 Assembly}}
{{omit from|8080 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|AArch64 Assembly}}
{{omit from|AArch64 Assembly}}
{{omit from|ARM Assembly}}
{{omit from|ARM Assembly}}