Call a function in a shared library: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
[[Category:Functions and subroutines]]
{{task|Programming environment operations}}
{{task|Programming environment operations}}
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
Line 8: Line 9:
* [[OpenGL]] -- OpenGL is usually maintained as a shared library.
* [[OpenGL]] -- OpenGL is usually maintained as a shared library.
<br><br>
<br><br>

=={{header|Ada}}==
=={{header|Ada}}==
===Windows===
===Windows===
The following solution calls ''MessageBox'' from [[Windows]]' dynamic library ''user32.dll''. It does not use Win32 bindings, which would be meaningless, because ''MessageBox'' is already there. Instead of that it links statically to ''kernel32.dll'', which required to load anything under [[Windows]]. From there it uses ''LoadLibrary'' to load ''user32.dll'' and then ''GetProcAddress'' to get the ''MessageBox'' entry point there. Note how [[Windows]] mangles names of functions in the import libraries. So "LoadLibrary" becomes "_LoadLibraryA@4", which is its real name. "A" means ASCII. Once address of ''MessageBox'' is obtained it is converted to a pointer to a function that has an interface corresponding to it. Note [[Windows]]' call convention, which is '''stdcall'''.
The following solution calls ''MessageBox'' from [[Windows]]' dynamic library ''user32.dll''. It does not use Win32 bindings, which would be meaningless, because ''MessageBox'' is already there. Instead of that it links statically to ''kernel32.dll'', which required to load anything under [[Windows]]. From there it uses ''LoadLibrary'' to load ''user32.dll'' and then ''GetProcAddress'' to get the ''MessageBox'' entry point there. Note how [[Windows]] mangles names of functions in the import libraries. So "LoadLibrary" becomes "_LoadLibraryA@4", which is its real name. "A" means ASCII. Once address of ''MessageBox'' is obtained it is converted to a pointer to a function that has an interface corresponding to it. Note [[Windows]]' call convention, which is '''stdcall'''.
<syntaxhighlight lang=Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
with Interfaces; use Interfaces;
with Interfaces.C; use Interfaces.C;
with Interfaces.C; use Interfaces.C;
Line 60: Line 60:
===Linux===
===Linux===
Here we are using the ''dl'' library statically (-ldl switch upon linking) and ''Xlib'' dynamically (''libX11.so''). The function ''dlopen'' loads a library. The function ''dlsym'' looks up for an entry point there. From ''libX11.so'', first ''XOpenDisplay'' is called to open an X11 display, which name is in the DISPLAY environment variable. Then XDisplayWidth of the display is obtained an printed into the standard output.
Here we are using the ''dl'' library statically (-ldl switch upon linking) and ''Xlib'' dynamically (''libX11.so''). The function ''dlopen'' loads a library. The function ''dlsym'' looks up for an entry point there. From ''libX11.so'', first ''XOpenDisplay'' is called to open an X11 display, which name is in the DISPLAY environment variable. Then XDisplayWidth of the display is obtained an printed into the standard output.
<syntaxhighlight lang=Ada>with Ada.Environment_Variables; use Ada.Environment_Variables;
<syntaxhighlight lang="ada">with Ada.Environment_Variables; use Ada.Environment_Variables;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
with Interfaces; use Interfaces;
Line 109: Line 109:
end if;
end if;
end Shared_Library_Call;</syntaxhighlight>
end Shared_Library_Call;</syntaxhighlight>

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


<syntaxhighlight lang=rebol>getCurlVersion: function [][
<syntaxhighlight lang="rebol">getCurlVersion: function [][
try? [
try? [
call.external:'curl "curl_version" .expect: :string []
call.external:'curl "curl_version" .expect: :string []
Line 126: Line 125:


<pre>curl version: libcurl/7.64.1 SecureTransport (LibreSSL/2.8.3) zlib/1.2.11 nghttp2/1.41.0 </pre>
<pre>curl version: libcurl/7.64.1 SecureTransport (LibreSSL/2.8.3) zlib/1.2.11 nghttp2/1.41.0 </pre>

=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with|http://www.autohotkey.net/~tinku99/ahkdll/ AutoHotkey.dll}}<br>
{{works with|http://www.autohotkey.net/~tinku99/ahkdll/ AutoHotkey.dll}}<br>
dllhost.ahk
dllhost.ahk
<syntaxhighlight lang=AutoHotkey>ahkdll := DllCall("LoadLibrary", "str", "AutoHotkey.dll")
<syntaxhighlight lang="autohotkey">ahkdll := DllCall("LoadLibrary", "str", "AutoHotkey.dll")
clientHandle := DllCall("AutoHotkey\ahkdll", "str", "dllclient.ahk", "str"
clientHandle := DllCall("AutoHotkey\ahkdll", "str", "dllclient.ahk", "str"
, "", "str", "parameter1 parameter2", "Cdecl Int")</syntaxhighlight>
, "", "str", "parameter1 parameter2", "Cdecl Int")</syntaxhighlight>
dllclient.ahk
dllclient.ahk
<syntaxhighlight lang=AutoHotkey>Msgbox, hello from client</syntaxhighlight>
<syntaxhighlight lang="autohotkey">Msgbox, hello from client</syntaxhighlight>

=={{header|BaCon}}==
=={{header|BaCon}}==


<syntaxhighlight lang=qbasic>' Call a dynamic library function
<syntaxhighlight lang="qbasic">' Call a dynamic library function
PROTO j0
PROTO j0
bessel0 = j0(1.0)
bessel0 = j0(1.0)
Line 152: Line 149:
prompt$ ./calllib
prompt$ ./calllib
0.765198</pre>
0.765198</pre>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
The following shared libraries are automatically available: ADVAPI32.DLL, COMCTL32.DLL, COMDLG32.DLL, GDI32.DLL, KERNEL32.DLL, SHELL32.DLL, USER32.DLL and WINMM.DLL.
The following shared libraries are automatically available: ADVAPI32.DLL, COMCTL32.DLL, COMDLG32.DLL, GDI32.DLL, KERNEL32.DLL, SHELL32.DLL, USER32.DLL and WINMM.DLL.
<syntaxhighlight lang=bbcbasic> SYS "MessageBox", @hwnd%, "This is a test message", 0, 0
<syntaxhighlight lang="bbcbasic"> SYS "MessageBox", @hwnd%, "This is a test message", 0, 0
</syntaxhighlight>
</syntaxhighlight>

=={{header|C}}==
=={{header|C}}==
{{works with|POSIX|.1-2001}}
{{works with|POSIX|.1-2001}}
Line 164: Line 159:
'''Tested with''' gcc on a GNU/Linux system (on GNU/Linux <code>dl*</code> functions are available linking to <tt>libdl</tt>, i.e. with <tt>-ldl</tt> option)
'''Tested with''' gcc on a GNU/Linux system (on GNU/Linux <code>dl*</code> functions are available linking to <tt>libdl</tt>, i.e. with <tt>-ldl</tt> option)


<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <dlfcn.h>
Line 203: Line 198:
The fake <tt>fakeimglib.so</tt> code is
The fake <tt>fakeimglib.so</tt> code is


<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */
/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
int openimage(const char *s)
Line 221: Line 216:
<pre>internal openimage opens fake.img...
<pre>internal openimage opens fake.img...
opened with handle 0</pre>
opened with handle 0</pre>

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
In Windows.
In Windows.
<syntaxhighlight lang=csharp>using System.Runtime.InteropServices;
<syntaxhighlight lang="csharp">using System.Runtime.InteropServices;


class Program {
class Program {
Line 234: Line 228:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|COBOL}}==
=={{header|COBOL}}==
Tested with GnuCOBOL, GNU/Linux.
Tested with GnuCOBOL, GNU/Linux.


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


Line 279: Line 272:
<pre>prompt$ cobc -xj callsym.cob
<pre>prompt$ cobc -xj callsym.cob
Success</pre>
Success</pre>

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


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


<syntaxhighlight lang=lisp>CL-USER> (cffi:load-foreign-library "libX11.so")
<syntaxhighlight lang="lisp">CL-USER> (cffi:load-foreign-library "libX11.so")
#<CFFI::FOREIGN-LIBRARY {1004F4ECC1}>
#<CFFI::FOREIGN-LIBRARY {1004F4ECC1}>
CL-USER> (cffi:foreign-funcall "XOpenDisplay"
CL-USER> (cffi:foreign-funcall "XOpenDisplay"
Line 291: Line 283:
:pointer)
:pointer)
#.(SB-SYS:INT-SAP #X00650FD0)</syntaxhighlight>
#.(SB-SYS:INT-SAP #X00650FD0)</syntaxhighlight>

=={{header|Crystal}}==
=={{header|Crystal}}==


<syntaxhighlight lang=ruby>libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
<syntaxhighlight lang="ruby">libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?


Line 305: Line 296:


puts "the sqrt of 4 is #{sqrtproc.call(4.0)}"</syntaxhighlight>
puts "the sqrt of 4 is #{sqrtproc.call(4.0)}"</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>pragma(lib, "user32.lib");
<syntaxhighlight lang="d">pragma(lib, "user32.lib");


import std.stdio, std.c.windows.windows;
import std.stdio, std.c.windows.windows;
Line 318: Line 308:


<pre>500</pre>
<pre>500</pre>

=={{header|Dart}}==
=={{header|Dart}}==


add.c
add.c
<syntaxhighlight lang=c>
<syntaxhighlight lang="c">
int add(int num1, int num2) {
int add(int num1, int num2) {
return num1 + num2;
return num1 + num2;
Line 329: Line 318:


Dart code
Dart code
<syntaxhighlight lang=javascript>import 'dart:ffi'
<syntaxhighlight lang="javascript">import 'dart:ffi'
show DynamicLibrary, NativeFunction, Int32;
show DynamicLibrary, NativeFunction, Int32;


Line 342: Line 331:
}
}
</syntaxhighlight>
</syntaxhighlight>

=={{header|Delphi}}==
=={{header|Delphi}}==


Line 348: Line 336:
Loads library on startup.
Loads library on startup.


<syntaxhighlight lang=Delphi>procedure DoSomething; external 'MYLIB.DLL';</syntaxhighlight>
<syntaxhighlight lang="delphi">procedure DoSomething; external 'MYLIB.DLL';</syntaxhighlight>




Line 354: Line 342:
Loads library on first call to DoSomething.
Loads library on first call to DoSomething.


<syntaxhighlight lang=Delphi>procedure DoSomething; external 'MYLIB.DLL' delayed;</syntaxhighlight>
<syntaxhighlight lang="delphi">procedure DoSomething; external 'MYLIB.DLL' delayed;</syntaxhighlight>




Line 360: Line 348:
Loads and unloads library on demand.
Loads and unloads library on demand.


<syntaxhighlight lang=Delphi>var
<syntaxhighlight lang="delphi">var
lLibraryHandle: THandle;
lLibraryHandle: THandle;
lDoSomething: procedure; stdcall;
lDoSomething: procedure; stdcall;
Line 372: Line 360:
end;
end;
end;</syntaxhighlight>
end;</syntaxhighlight>

=={{header|Forth}}==
=={{header|Forth}}==
===GNU Forth 0.7.9 on Linux===
===GNU Forth 0.7.9 on Linux===
Call tgamma() from limbm.so
Call tgamma() from limbm.so
<syntaxhighlight lang=Forth>
<syntaxhighlight lang="forth">
c-library math
c-library math


Line 390: Line 377:
1.01e2 gamma fs. 9.33262154439442E157 ok
1.01e2 gamma fs. 9.33262154439442E157 ok
</pre>
</pre>

=={{header|Fortran}}==
=={{header|Fortran}}==
===GNU Fortran on Linux===
===GNU Fortran on Linux===
Line 398: Line 384:


A simple "C" function add_n in add_n.c
A simple "C" function add_n in add_n.c
<syntaxhighlight lang=c>
<syntaxhighlight lang="c">
double add_n(double* a, double* b)
double add_n(double* a, double* b)
{
{
Line 412: Line 398:


File add_nf.f90
File add_nf.f90
<syntaxhighlight lang=fortran>
<syntaxhighlight lang="fortran">
function add_nf(a,b) bind(c, name='add_nf')
function add_nf(a,b) bind(c, name='add_nf')
use, intrinsic :: iso_c_binding
use, intrinsic :: iso_c_binding
Line 434: Line 420:


File shared_lib_new_test.f90
File shared_lib_new_test.f90
<syntaxhighlight lang=fortran>
<syntaxhighlight lang="fortran">
!-----------------------------------------------------------------------
!-----------------------------------------------------------------------
!module dll_module
!module dll_module
Line 732: Line 718:
===Intel Fortran on Windows===
===Intel Fortran on Windows===
First, the DLL. Compile with '''ifort /dll dllfun.f90'''. The function is compiled with the STDCALL calling convention: it's not necessary here but it shows how to do it.
First, the DLL. Compile with '''ifort /dll dllfun.f90'''. The function is compiled with the STDCALL calling convention: it's not necessary here but it shows how to do it.
<syntaxhighlight lang=fortran>function ffun(x, y)
<syntaxhighlight lang="fortran">function ffun(x, y)
implicit none
implicit none
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: FFUN
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: FFUN
Line 741: Line 727:
Now, the main program. It will wait for two numbers and compute the result with the DLL function. Compile with '''ifort dynload.f90'''. Three functions of the Kernel32 library are necessary, see '''[https://msdn.microsoft.com/en-us/library/ms684175.aspx LoadLibrary]''', '''[https://msdn.microsoft.com/en-us/library/ms683212.aspx GetProcAddress]''' and '''[https://msdn.microsoft.com/en-us/library/ms683152.aspx FreeLibrary]''' in the MSDN. The kernel32 module is provided with the Intel Fortran compiler. The DLL has to be in a directory in the PATH environment variable.
Now, the main program. It will wait for two numbers and compute the result with the DLL function. Compile with '''ifort dynload.f90'''. Three functions of the Kernel32 library are necessary, see '''[https://msdn.microsoft.com/en-us/library/ms684175.aspx LoadLibrary]''', '''[https://msdn.microsoft.com/en-us/library/ms683212.aspx GetProcAddress]''' and '''[https://msdn.microsoft.com/en-us/library/ms683152.aspx FreeLibrary]''' in the MSDN. The kernel32 module is provided with the Intel Fortran compiler. The DLL has to be in a directory in the PATH environment variable.


<syntaxhighlight lang=fortran>program dynload
<syntaxhighlight lang="fortran">program dynload
use kernel32
use kernel32
use iso_c_binding
use iso_c_binding
Line 784: Line 770:


First the DLL:
First the DLL:
<syntaxhighlight lang=fortran>function ffun(x, y)
<syntaxhighlight lang="fortran">function ffun(x, y)
implicit none
implicit none
!GCC$ ATTRIBUTES DLLEXPORT, STDCALL :: FFUN
!GCC$ ATTRIBUTES DLLEXPORT, STDCALL :: FFUN
Line 792: Line 778:


Main program:
Main program:
<syntaxhighlight lang=fortran>program dynload
<syntaxhighlight lang="fortran">program dynload
use kernel32
use kernel32
use iso_c_binding
use iso_c_binding
Line 824: Line 810:


Interface module:
Interface module:
<syntaxhighlight lang=fortran>module kernel32
<syntaxhighlight lang="fortran">module kernel32
use iso_c_binding
use iso_c_binding
implicit none
implicit none
Line 859: Line 845:
end interface
end interface
end module</syntaxhighlight>
end module</syntaxhighlight>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


' Attempt to call Beep function in Win32 API
' Attempt to call Beep function in Win32 API
Line 884: Line 869:
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</syntaxhighlight>
Sleep</syntaxhighlight>

=={{header|Go}}==
=={{header|Go}}==
{{trans|C}}
{{trans|C}}
Line 892: Line 876:


This is the C code to produce fakeimglib.so:
This is the C code to produce fakeimglib.so:
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
int openimage(const char *s)
Line 901: Line 885:
}</syntaxhighlight>
}</syntaxhighlight>
And this is the Go code to dynamically load the .so file and call the 'openimage' function - or if the .so file (or the function itself) is not available, to call the internal version of the function:
And this is the Go code to dynamically load the .so file and call the 'openimage' function - or if the .so file (or the function itself) is not available, to call the internal version of the function:
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


/*
/*
Line 958: Line 942:
Same as C entry.
Same as C entry.
</pre>
</pre>

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


Line 964: Line 947:
{{libheader|unix}}
{{libheader|unix}}


<syntaxhighlight lang=haskell>#!/usr/bin/env stack
<syntaxhighlight lang="haskell">#!/usr/bin/env stack
-- stack --resolver lts-6.33 --install-ghc runghc --package unix
-- stack --resolver lts-6.33 --install-ghc runghc --package unix


Line 1,005: Line 988:
putStrLn msg
putStrLn msg
putStrLn $ rev "a man a plan a canal panama"</syntaxhighlight>
putStrLn $ rev "a man a plan a canal panama"</syntaxhighlight>

=={{header|J}}==
=={{header|J}}==
Most of this was borrowed from [[Call a foreign-language function#J]]
Most of this was borrowed from [[Call a foreign-language function#J]]
<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,024: Line 1,006:


Example use:
Example use:
<syntaxhighlight lang=J> DupStr 'hello'
<syntaxhighlight lang="j"> DupStr 'hello'
hello
hello
getstr@strdup ::] 'hello'
getstr@strdup ::] 'hello'
hello</syntaxhighlight>
hello</syntaxhighlight>

=={{header|Java}}==
=={{header|Java}}==
For methods with the <tt>native</tt> keyword, the library must be written to the [[wp:Java Native Interface|Java Native Interface]]; this is not a general [[FFI]]. If the library is missing, <code>System.loadLibrary()</code> throws <code>UnsatisfiedLinkError</code>. We can continue if we catch this error and then don't call the library's native methods.
For methods with the <tt>native</tt> keyword, the library must be written to the [[wp:Java Native Interface|Java Native Interface]]; this is not a general [[FFI]]. If the library is missing, <code>System.loadLibrary()</code> throws <code>UnsatisfiedLinkError</code>. We can continue if we catch this error and then don't call the library's native methods.
Line 1,034: Line 1,015:
If you have Unix [[make]], then edit the ''Makefile'', run <code>make</code>, run <code>java -Djava.library.path=. RSort</code>. If you don't set java.library.path, or don't build the library, then the Java code falls back from using C to using Java. For more info about building a JNI library, see [[Call a foreign-language function#Java]].
If you have Unix [[make]], then edit the ''Makefile'', run <code>make</code>, run <code>java -Djava.library.path=. RSort</code>. If you don't set java.library.path, or don't build the library, then the Java code falls back from using C to using Java. For more info about building a JNI library, see [[Call a foreign-language function#Java]].


<syntaxhighlight lang=java>/* TrySort.java */
<syntaxhighlight lang="java">/* TrySort.java */


import java.util.Collections;
import java.util.Collections;
Line 1,106: Line 1,087:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=c>/* TrySort.c */
<syntaxhighlight lang="c">/* TrySort.c */


#include <stdlib.h>
#include <stdlib.h>
Line 1,141: Line 1,122:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=make># Makefile
<syntaxhighlight lang="make"># Makefile


# Edit the next lines to match your JDK.
# Edit the next lines to match your JDK.
Line 1,171: Line 1,152:
===JNA===
===JNA===
{{libheader|JNA}}
{{libheader|JNA}}
<syntaxhighlight lang=java>import com.sun.jna.Library;
<syntaxhighlight lang="java">import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Native;


Line 1,186: Line 1,167:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Jsish}}==
=={{header|Jsish}}==
Jsish includes a '''load('library.so');''' function, which calls a specially crafted management function in the library,
Jsish includes a '''load('library.so');''' function, which calls a specially crafted management function in the library,
Line 1,193: Line 1,173:
Normally, this function would register commands to the shell, but this is just a DISPLAY statement on load, and then again on unload as jsish runs down. Note the name used, "Jsi_Initbyjsi", from "byjsi.so".
Normally, this function would register commands to the shell, but this is just a DISPLAY statement on load, and then again on unload as jsish runs down. Note the name used, "Jsi_Initbyjsi", from "byjsi.so".


<syntaxhighlight lang=javascript>#!/usr/local/bin/jsish
<syntaxhighlight lang="javascript">#!/usr/local/bin/jsish
load('byjsi.so');</syntaxhighlight>
load('byjsi.so');</syntaxhighlight>


For example, a COBOL library generated from
For example, a COBOL library generated from


<syntaxhighlight lang=COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. sample as "Jsi_Initbyjsi".
program-id. sample as "Jsi_Initbyjsi".


Line 1,231: Line 1,211:
Called again with: 0x00000000013a9260, +0000000002
Called again with: 0x00000000013a9260, +0000000002
prompt$</pre>
prompt$</pre>

=={{header|Julia}}==
=={{header|Julia}}==
Julia has the `ccall` function which follows the form: ccall((symbol, library), RetType, (ArgType1, ...), ArgVar1, ...)
Julia has the `ccall` function which follows the form: ccall((symbol, library), RetType, (ArgType1, ...), ArgVar1, ...)
<syntaxhighlight lang=julia>
<syntaxhighlight lang="julia">
#this example works on Windows
#this example works on Windows
ccall( (:GetDoubleClickTime, "User32"), stdcall,
ccall( (:GetDoubleClickTime, "User32"), stdcall,
Line 1,241: Line 1,220:
ccall( (:clock, "libc"), Int32, ())</syntaxhighlight>
ccall( (:clock, "libc"), Int32, ())</syntaxhighlight>
For more information, see here [http://docs.julialang.org/en/latest/manual/calling-c-and-fortran-code.html]
For more information, see here [http://docs.julialang.org/en/latest/manual/calling-c-and-fortran-code.html]

=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|C}}
{{trans|C}}
Line 1,247: Line 1,225:


This is the C code to produce fakeimglib.so:
This is the C code to produce fakeimglib.so:
<syntaxhighlight lang=C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
int openimage(const char *s)
Line 1,256: Line 1,234:
}</syntaxhighlight>
}</syntaxhighlight>
And this is the Kotlin code to dynamically load the .so file and call the 'openimage' function - or if the .so file (or the function itself) is not available, to call the internal version of the function:
And this is the Kotlin code to dynamically load the .so file and call the 'openimage' function - or if the .so file (or the function itself) is not available, to call the internal version of the function:
<syntaxhighlight lang=scala>// Kotlin Native version 0.5
<syntaxhighlight lang="scala">// Kotlin Native version 0.5


import kotlinx.cinterop.*
import kotlinx.cinterop.*
Line 1,295: Line 1,273:
Same as C entry
Same as C entry
</pre>
</pre>

=={{header|Lingo}}==
=={{header|Lingo}}==
<syntaxhighlight lang=lingo>-- calculate CRC-32 checksum
<syntaxhighlight lang="lingo">-- calculate CRC-32 checksum
str = "The quick brown fox jumps over the lazy dog"
str = "The quick brown fox jumps over the lazy dog"


Line 1,315: Line 1,292:


end if</syntaxhighlight>
end if</syntaxhighlight>

=={{header|Lua}}==
=={{header|Lua}}==
There is no built-in mechanism, but several external library options exist. Here, the alien library is used to display a message box via the Win32 API.
There is no built-in mechanism, but several external library options exist. Here, the alien library is used to display a message box via the Win32 API.
<syntaxhighlight lang=lua>alien = require("alien")
<syntaxhighlight lang="lua">alien = require("alien")
msgbox = alien.User32.MessageBoxA
msgbox = alien.User32.MessageBoxA
msgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' })
msgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' })
retval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3)
retval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3)
print(retval) --> 6, 7 or 2</syntaxhighlight>
print(retval) --> 6, 7 or 2</syntaxhighlight>

=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang=Maple>> cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = "libm.so" ):
<syntaxhighlight lang="maple">> cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = "libm.so" ):
> cfloor( 2.3 );
> cfloor( 2.3 );
2.</syntaxhighlight>
2.</syntaxhighlight>

=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This works on windows and on linux/mac too (through Mono)
This works on windows and on linux/mac too (through Mono)
<syntaxhighlight lang=Mathematica>Needs["NETLink`"];
<syntaxhighlight lang="mathematica">Needs["NETLink`"];
externalFloor = DefineDLLFunction["floor", "msvcrt.dll", "double", { "double" }];
externalFloor = DefineDLLFunction["floor", "msvcrt.dll", "double", { "double" }];
externalFloor[4.2]
externalFloor[4.2]
-> 4.</syntaxhighlight>
-> 4.</syntaxhighlight>

=={{header|Nim}}==
=={{header|Nim}}==
===Interacting with C code===
===Interacting with C code===
<syntaxhighlight lang=nim>proc openimage(s: cstring): cint {.importc, dynlib: "./fakeimglib.so".}
<syntaxhighlight lang="nim">proc openimage(s: cstring): cint {.importc, dynlib: "./fakeimglib.so".}


echo openimage("foo")
echo openimage("foo")
Line 1,344: Line 1,317:
echo openimage("baz")</syntaxhighlight>
echo openimage("baz")</syntaxhighlight>
The fake <code>fakeimglib.so</code> code is
The fake <code>fakeimglib.so</code> code is
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */
/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
int openimage(const char *s)
Line 1,361: Line 1,334:


===Interacting with Nim code===
===Interacting with Nim code===
<syntaxhighlight lang=nim>proc openimage(s: string): int {.importc, dynlib: "./libfakeimg.so".}
<syntaxhighlight lang="nim">proc openimage(s: string): int {.importc, dynlib: "./libfakeimg.so".}


echo openimage("foo")
echo openimage("foo")
Line 1,367: Line 1,340:
echo openimage("baz")</syntaxhighlight>
echo openimage("baz")</syntaxhighlight>
The fake <code>libfakeimg.so</code> code is
The fake <code>libfakeimg.so</code> code is
<syntaxhighlight lang=nim># nim c --app:lib fakeimg.nim
<syntaxhighlight lang="nim"># nim c --app:lib fakeimg.nim
var handle = 100
var handle = 100


Line 1,381: Line 1,354:
opening baz
opening baz
102</pre>
102</pre>

=={{header|OCaml}}==
=={{header|OCaml}}==
As far as I know there is no solution in OCaml standard library to load a function from a C library dynamically. So I have quickly implemented [[Call a function in a shared library/OCaml|a module named Dlffi that you can find in this sub-page]]. It is basically a wrapper around the GNU/Linux dl* functions and the libffi.
As far as I know there is no solution in OCaml standard library to load a function from a C library dynamically. So I have quickly implemented [[Call a function in a shared library/OCaml|a module named Dlffi that you can find in this sub-page]]. It is basically a wrapper around the GNU/Linux dl* functions and the libffi.
Line 1,388: Line 1,360:


Here is an example of use of this [[Call a function in a shared library/OCaml|Dlffi module]]:
Here is an example of use of this [[Call a function in a shared library/OCaml|Dlffi module]]:
<syntaxhighlight lang=ocaml>open Dlffi
<syntaxhighlight lang="ocaml">open Dlffi


let get_int = function Int v -> v | _ -> failwith "get_int"
let get_int = function Int v -> v | _ -> failwith "get_int"
Line 1,419: Line 1,391:
dlclose xlib;
dlclose xlib;
;;</syntaxhighlight>
;;</syntaxhighlight>

=={{header|Ol}}==
=={{header|Ol}}==


Simplest case. Will produce memory leak, because no C "free" function called for dupped string. Useful when no "free" function call required.
Simplest case. Will produce memory leak, because no C "free" function called for dupped string. Useful when no "free" function call required.
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(import (otus ffi))
(import (otus ffi))


Line 1,434: Line 1,405:


A bit complex case. No memory leaks, because "free" function called for dupped string.
A bit complex case. No memory leaks, because "free" function called for dupped string.
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(import (otus ffi))
(import (otus ffi))


Line 1,454: Line 1,425:
Hello World!
Hello World!
</pre>
</pre>

=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<syntaxhighlight lang=oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
'Loading a shared library at run time and calling a function.
'Loading a shared library at run time and calling a function.


Line 1,471: Line 1,441:
FreeLibrary user32
FreeLibrary user32
</syntaxhighlight>
</syntaxhighlight>

=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<syntaxhighlight lang=parigp>install("function_name","G","gp_name","./test.gp.so");</syntaxhighlight>
<syntaxhighlight lang="parigp">install("function_name","G","gp_name","./test.gp.so");</syntaxhighlight>
where "G" is the parser code; see section 5.7.3 in the [http://pari.math.u-bordeaux.fr/pub/pari/manuals/2.4.4/libpari.pdf User's Guide to the PARI library] for more information.
where "G" is the parser code; see section 5.7.3 in the [http://pari.math.u-bordeaux.fr/pub/pari/manuals/2.4.4/libpari.pdf User's Guide to the PARI library] for more information.

=={{header|Pascal}}==
=={{header|Pascal}}==
See [[Call_a_function_in_a_shared_library#Delphi | Delphi]]
See [[Call_a_function_in_a_shared_library#Delphi | Delphi]]

=={{header|Perl}}==
=={{header|Perl}}==
Examples for simple <code>C</code> library calls, but each module is capable of much more (and can work with other languages). Refer to their documentation for details.
Examples for simple <code>C</code> library calls, but each module is capable of much more (and can work with other languages). Refer to their documentation for details.
===Inline===
===Inline===
This modules auto-builds a wrapper to the library on the first call, and subsequently uses that interface with no delay.
This modules auto-builds a wrapper to the library on the first call, and subsequently uses that interface with no delay.
<syntaxhighlight lang=perl>use Inline
<syntaxhighlight lang="perl">use Inline
C => "DATA",
C => "DATA",
ENABLE => "AUTOWRAP",
ENABLE => "AUTOWRAP",
Line 1,497: Line 1,464:
===FFI===
===FFI===
This module is smart about finding libraries, here getting <code>atan</code> (from 'lm') and <code>puts</code> (from 'libc').
This module is smart about finding libraries, here getting <code>atan</code> (from 'lm') and <code>puts</code> (from 'libc').
<syntaxhighlight lang=perl>use FFI::Platypus;
<syntaxhighlight lang="perl">use FFI::Platypus;
my $ffi = FFI::Platypus->new;
my $ffi = FFI::Platypus->new;
$ffi->lib(undef);
$ffi->lib(undef);
Line 1,506: Line 1,473:
{{out}}
{{out}}
<pre>3.14159265358979</pre>
<pre>3.14159265358979</pre>

=={{header|Phix}}==
=={{header|Phix}}==
<!--<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: #004080;">string</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">libname</span><span style="color: #0000FF;">,</span><span style="color: #000000;">funcname</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">WINDOWS</span><span style="color: #0000FF;">?{</span><span style="color: #008000;">"user32"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"CharLowerA"</span><span style="color: #0000FF;">}:{</span><span style="color: #008000;">"libc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"tolower"</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">string</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">libname</span><span style="color: #0000FF;">,</span><span style="color: #000000;">funcname</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">WINDOWS</span><span style="color: #0000FF;">?{</span><span style="color: #008000;">"user32"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"CharLowerA"</span><span style="color: #0000FF;">}:{</span><span style="color: #008000;">"libc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"tolower"</span><span style="color: #0000FF;">})</span>
Line 1,523: Line 1,489:
97 -- (or {{97}} if func not found)
97 -- (or {{97}} if func not found)
</pre>
</pre>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
This differs between the 32-bit and 64-bit versions. While the 64-bit version
This differs between the 32-bit and 64-bit versions. While the 64-bit version
Line 1,530: Line 1,495:
===32-bit version===
===32-bit version===
For the 32-bit version, we need some glue code:
For the 32-bit version, we need some glue code:
<syntaxhighlight lang=PicoLisp>(load "@lib/gcc.l")
<syntaxhighlight lang="picolisp">(load "@lib/gcc.l")


(gcc "x11" '("-lX11") 'xOpenDisplay 'xCloseDisplay)
(gcc "x11" '("-lX11") 'xOpenDisplay 'xCloseDisplay)
Line 1,558: Line 1,523:
===64-bit version===
===64-bit version===
In the 64-bit version, we can call the library directly:
In the 64-bit version, we can call the library directly:
<syntaxhighlight lang=PicoLisp>: (setq Display (native "/usr/lib/libX11.so.6" "XOpenDisplay" 'N ":0.0"))
<syntaxhighlight lang="picolisp">: (setq Display (native "/usr/lib/libX11.so.6" "XOpenDisplay" 'N ":0.0"))
-> 6502688
-> 6502688
: (native "/usr/lib/libX11.so.6" "XCloseDisplay" 'I Display)
: (native "/usr/lib/libX11.so.6" "XCloseDisplay" 'I Display)
-> 0</syntaxhighlight>
-> 0</syntaxhighlight>

=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
{{Works with|PowerBASIC for Windows}}
{{Works with|PowerBASIC for Windows}}
In this example, if the library can't be found (user32), or the desired function in the library (MessageBoxA), the equivalent built-in function (MSGBOX) is at the "epicFail" label... but really, if you can't find user32.dll, you've got bigger things to worry about.
In this example, if the library can't be found (user32), or the desired function in the library (MessageBoxA), the equivalent built-in function (MSGBOX) is at the "epicFail" label... but really, if you can't find user32.dll, you've got bigger things to worry about.
<syntaxhighlight lang=powerbasic>#INCLUDE "Win32API.inc"
<syntaxhighlight lang="powerbasic">#INCLUDE "Win32API.inc"


FUNCTION PBMAIN () AS LONG
FUNCTION PBMAIN () AS LONG
Line 1,603: Line 1,567:
END IF
END IF
END FUNCTION</syntaxhighlight>
END FUNCTION</syntaxhighlight>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
Older PureBasic versions normally relied on CallFunction() and CallFunctionFast()
Older PureBasic versions normally relied on CallFunction() and CallFunctionFast()
<syntaxhighlight lang=Purebasic>if OpenLibrary(0, "USER32.DLL")
<syntaxhighlight lang="purebasic">if OpenLibrary(0, "USER32.DLL")
*MessageBox = GetFunction(0, "MessageBoxA")
*MessageBox = GetFunction(0, "MessageBoxA")
CallFunctionFast(*MessageBox, 0, "Body", "Title", 0)
CallFunctionFast(*MessageBox, 0, "Body", "Title", 0)
Line 1,612: Line 1,575:
endif</syntaxhighlight>
endif</syntaxhighlight>
Since versions 4 the recommended way is via the usage of Prototypes even if the old system still is supported.
Since versions 4 the recommended way is via the usage of Prototypes even if the old system still is supported.
<syntaxhighlight lang=PureBasic>Prototype.l ProtoMessageBoxW(Window.l, Body.p-unicode, Title.p-unicode, Flags.l = 0)
<syntaxhighlight lang="purebasic">Prototype.l ProtoMessageBoxW(Window.l, Body.p-unicode, Title.p-unicode, Flags.l = 0)


If OpenLibrary(0, "User32.dll")
If OpenLibrary(0, "User32.dll")
Line 1,619: Line 1,582:
CloseLibrary(0)
CloseLibrary(0)
EndIf</syntaxhighlight>
EndIf</syntaxhighlight>

=={{header|Python}}==
=={{header|Python}}==
=== ctypes ===
=== ctypes ===
Example that call User32.dll::GetDoubleClickTime() in windows.
Example that call User32.dll::GetDoubleClickTime() in windows.
<syntaxhighlight lang=python>import ctypes
<syntaxhighlight lang="python">import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()</syntaxhighlight>
print user32_dll.GetDoubleClickTime()</syntaxhighlight>
Or, to call printf out of the C standard library:
Or, to call printf out of the C standard library:
<syntaxhighlight lang=python>>>> import ctypes
<syntaxhighlight lang="python">>>> import ctypes
>>> # libc = ctypes.cdll.msvcrt # Windows
>>> # libc = ctypes.cdll.msvcrt # Windows
>>> # libc = ctypes.CDLL('libc.dylib') # Mac
>>> # libc = ctypes.CDLL('libc.dylib') # Mac
Line 1,638: Line 1,600:
=== CFFI ===
=== CFFI ===
[https://cffi.readthedocs.io/ CFFI] isn't built into the stdlib, but, on the other hand, it works with other Python implementations like PyPy. It also has a variety of advantages and disadvantages over ctypes, even for simple cases like this:
[https://cffi.readthedocs.io/ CFFI] isn't built into the stdlib, but, on the other hand, it works with other Python implementations like PyPy. It also has a variety of advantages and disadvantages over ctypes, even for simple cases like this:
<syntaxhighlight lang=python>
<syntaxhighlight lang="python">
>>> from cffi import FFI
>>> from cffi import FFI
>>> ffi = FFI()
>>> ffi = FFI()
Line 1,650: Line 1,612:
17</syntaxhighlight>
17</syntaxhighlight>
=={{header|QB64}}==
=={{header|QB64}}==
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
Declare Dynamic Library "Kernel32"
Declare Dynamic Library "Kernel32"
Sub SetLastError (ByVal dwErr As Long)
Sub SetLastError (ByVal dwErr As Long)
Line 1,658: Line 1,620:
SetLastError 20
SetLastError 20
Print GetLastError</syntaxhighlight>
Print GetLastError</syntaxhighlight>

=={{header|R}}==
=={{header|R}}==
This is possible in R in only a few limited ways. If the library function one wishes to call is a (C-level) R function (of type SEXP), then one may call
This is possible in R in only a few limited ways. If the library function one wishes to call is a (C-level) R function (of type SEXP), then one may call
<syntaxhighlight lang=rsplus>dyn.load("my/special/R/lib.so")
<syntaxhighlight lang="rsplus">dyn.load("my/special/R/lib.so")
.Call("my_lib_fun", arg1, arg2)</syntaxhighlight>
.Call("my_lib_fun", arg1, arg2)</syntaxhighlight>
It is also possible to use <code>.C()</code> and <code>.Fortran()</code> to call voids and subroutines respectively; here the return value(s) should be in the argument list (rather than merely modifying state). An example of this might look like
It is also possible to use <code>.C()</code> and <code>.Fortran()</code> to call voids and subroutines respectively; here the return value(s) should be in the argument list (rather than merely modifying state). An example of this might look like
<syntaxhighlight lang=rsplus>.C("my_lib_fun", arg1, arg2, ret)</syntaxhighlight>
<syntaxhighlight lang="rsplus">.C("my_lib_fun", arg1, arg2, ret)</syntaxhighlight>
The return of the <code>.C()</code> function is an R list.
The return of the <code>.C()</code> function is an R list.

=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(require ffi/unsafe)
(require ffi/unsafe)
(define libm (ffi-lib "libm")) ; get a handle for the C math library
(define libm (ffi-lib "libm")) ; get a handle for the C math library
Line 1,677: Line 1,637:
Output: <pre>> (extern-sqrt 42.0)
Output: <pre>> (extern-sqrt 42.0)
6.48074069840786</pre>
6.48074069840786</pre>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2018.11}}
{{works with|Rakudo|2018.11}}
<syntaxhighlight lang=raku line>use NativeCall;
<syntaxhighlight lang="raku" line>use NativeCall;


sub XOpenDisplay(Str $s --> int64) is native('X11') {*}
sub XOpenDisplay(Str $s --> int64) is native('X11') {*}
Line 1,696: Line 1,655:
{{out}}
{{out}}
<pre>ID = 94722089782960</pre>
<pre>ID = 94722089782960</pre>

=={{header|REXX}}==
=={{header|REXX}}==
{{works with|Regina REXX}}
{{works with|Regina REXX}}
Line 1,705: Line 1,663:


The dropping of functions isn't really necessary for most REXX programs.
The dropping of functions isn't really necessary for most REXX programs.
<syntaxhighlight lang=rexx>/*REXX program calls a function (sysTextScreenSize) in a shared library (regUtil). */
<syntaxhighlight lang="rexx">/*REXX program calls a function (sysTextScreenSize) in a shared library (regUtil). */


/*Note: the REGUTIL.DLL (REGina UTILity Dynamic Link Library */
/*Note: the REGUTIL.DLL (REGina UTILity Dynamic Link Library */
Line 1,738: Line 1,696:
cols= 96
cols= 96
</pre>
</pre>

=={{header|Ruby}}==
=={{header|Ruby}}==
This script uses Fiddle from Ruby's standard library to open <code>fakeimglib.so</code> from the [[#C|C example]].
This script uses Fiddle from Ruby's standard library to open <code>fakeimglib.so</code> from the [[#C|C example]].


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


module FakeImgLib
module FakeImgLib
Line 1,769: Line 1,726:
{{libheader|RubyGems}}
{{libheader|RubyGems}}
{{works with|Ruby|1.9+}}
{{works with|Ruby|1.9+}}
<syntaxhighlight lang=ruby># This script shows the width x height of some images.
<syntaxhighlight lang="ruby"># This script shows the width x height of some images.
# Example:
# Example:
# $ ruby imsize.rb dwarf-vs-elf.png swedish-chef.jpg
# $ ruby imsize.rb dwarf-vs-elf.png swedish-chef.jpg
Line 1,841: Line 1,798:
end
end
exit status</syntaxhighlight>
exit status</syntaxhighlight>

=={{header|Rust}}==
=={{header|Rust}}==
The standard library does not provide a way to load dynamic libraries. Without using third-party libraries, we must use the FFI to call the relevant C functions directly.
The standard library does not provide a way to load dynamic libraries. Without using third-party libraries, we must use the FFI to call the relevant C functions directly.


===Unix===
===Unix===
<syntaxhighlight lang=rust>#![allow(unused_unsafe)]
<syntaxhighlight lang="rust">#![allow(unused_unsafe)]
extern crate libc;
extern crate libc;


Line 1,884: Line 1,840:
x.cos()
x.cos()
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==
===Windows===
===Windows===
====Get free disk space====
====Get free disk space====
{{libheader|net.java.dev.sna.SNA}}
{{libheader|net.java.dev.sna.SNA}}
<syntaxhighlight lang=Scala>import net.java.dev.sna.SNA
<syntaxhighlight lang="scala">import net.java.dev.sna.SNA
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.IntByReference


Line 1,915: Line 1,870:
f" free-clusters: ${fc.getValue}%d, total/clusters: ${tc.getValue}%d%n")
f" free-clusters: ${fc.getValue}%d, total/clusters: ${tc.getValue}%d%n")
}}</syntaxhighlight>
}}</syntaxhighlight>

=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
The code tries to load the <tt>fakeimglib</tt> (cfr [[Call function in shared library#C|C example]]); if it succeed, the symbol <tt>openimage</tt> will exist, and will be called; otherwise, it is executed an "internal" code for <tt>openimage</tt>. In this example return code of the function of the library is ignored (<tt>ValueHolder null</tt>)
The code tries to load the <tt>fakeimglib</tt> (cfr [[Call function in shared library#C|C example]]); if it succeed, the symbol <tt>openimage</tt> will exist, and will be called; otherwise, it is executed an "internal" code for <tt>openimage</tt>. In this example return code of the function of the library is ignored (<tt>ValueHolder null</tt>)
<syntaxhighlight lang=smalltalk>DLD addLibrary: 'fakeimglib'.
<syntaxhighlight lang="smalltalk">DLD addLibrary: 'fakeimglib'.


Object subclass: ExtLib [
Object subclass: ExtLib [
Line 1,933: Line 1,887:


ExtLib openimage: 'test.png'.</syntaxhighlight>
ExtLib openimage: 'test.png'.</syntaxhighlight>

=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
{{works with|CSNOBOL4}}
{{works with|CSNOBOL4}}
This code loads the <tt>libm</tt> library into the variable <tt>ffi_m</tt> and binds the <tt>hypot()</tt> function to the variable <tt>ffi_m_hypot</tt>. (The variable names are arbitrary.) It then declares a SNOBOL4 function called <tt>hypot()</tt> which takes two <tt>double</tt>s as arguments and returns a <tt>double</tt>, binding this name to the <tt>ffi_m_hypot</tt> object returned earlier. It then outputs four hypotenuse calculations using those values.
This code loads the <tt>libm</tt> library into the variable <tt>ffi_m</tt> and binds the <tt>hypot()</tt> function to the variable <tt>ffi_m_hypot</tt>. (The variable names are arbitrary.) It then declares a SNOBOL4 function called <tt>hypot()</tt> which takes two <tt>double</tt>s as arguments and returns a <tt>double</tt>, binding this name to the <tt>ffi_m_hypot</tt> object returned earlier. It then outputs four hypotenuse calculations using those values.
<syntaxhighlight lang=snobol4>-INCLUDE 'ffi.sno'
<syntaxhighlight lang="snobol4">-INCLUDE 'ffi.sno'


ffi_m = FFI_DLOPEN('/usr/lib/x86_64-linux-gnu/libm.so')
ffi_m = FFI_DLOPEN('/usr/lib/x86_64-linux-gnu/libm.so')
Line 1,957: Line 1,910:
5.
5.
6.40312423743285</pre>
6.40312423743285</pre>

=={{header|Tcl}}==
=={{header|Tcl}}==
{{libheader|Ffidl}}
{{libheader|Ffidl}}
<syntaxhighlight lang=Tcl>package require Ffidl
<syntaxhighlight lang="tcl">package require Ffidl


if {[catch {
if {[catch {
Line 1,971: Line 1,923:


With this many ways to perform the call, the best approach often depends on the size and complexity of the API being mapped. SWIG excels at large APIs, Ffidl is better when you just want to call a particular simple function, and critcl handles complex cases (callbacks, etc.) better than the other two.
With this many ways to perform the call, the best approach often depends on the size and complexity of the API being mapped. SWIG excels at large APIs, Ffidl is better when you just want to call a particular simple function, and critcl handles complex cases (callbacks, etc.) better than the other two.

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


Line 2,004: Line 1,955:


The <code>nil</code> argument in the <code>with-dyn-lib</code> macro causes the underlying implementation to call <code>dlopen(NULL)</code> to get access to the dynamic symbols available in the executable. We can use the name of a shared library instead, or a handle from TXR's <code>dlopen</code> library function.
The <code>nil</code> argument in the <code>with-dyn-lib</code> macro causes the underlying implementation to call <code>dlopen(NULL)</code> to get access to the dynamic symbols available in the executable. We can use the name of a shared library instead, or a handle from TXR's <code>dlopen</code> library function.

=={{header|Ursala}}==
=={{header|Ursala}}==
When abs(x) is evaluated, a run time check is performed for the
When abs(x) is evaluated, a run time check is performed for the
Line 2,010: Line 1,960:
and if found, it is used. If not, the user defined replacement
and if found, it is used. If not, the user defined replacement
function is invoked.
function is invoked.
<syntaxhighlight lang=Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import flo
#import flo


Line 2,016: Line 1,966:


abs = math.|fabs my_replacement</syntaxhighlight>
abs = math.|fabs my_replacement</syntaxhighlight>

=={{header|VBA}}==
=={{header|VBA}}==
Here is an example using a Fortran function compiled as a DLL, using Intel Fortran.
Here is an example using a Fortran function compiled as a DLL, using Intel Fortran.
Line 2,022: Line 1,971:
First the DLL. Compile with '''ifort /dll vbafun.f90'''. The DLL must be in a directory in the PATH environment variable. Notice that for 32 bits VBA, DLL functions must be STDCALL, and not CDECL (the default with Intel Fortran). In 64 bits, there is only one calling convention, so it's not a problem anymore.
First the DLL. Compile with '''ifort /dll vbafun.f90'''. The DLL must be in a directory in the PATH environment variable. Notice that for 32 bits VBA, DLL functions must be STDCALL, and not CDECL (the default with Intel Fortran). In 64 bits, there is only one calling convention, so it's not a problem anymore.


<syntaxhighlight lang=fortran>function ffun(x, y)
<syntaxhighlight lang="fortran">function ffun(x, y)
implicit none
implicit none
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: ffun
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: ffun
Line 2,031: Line 1,980:
Here is a VBA subroutine using the DLL
Here is a VBA subroutine using the DLL


<syntaxhighlight lang=vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit
Declare Function ffun Lib "vbafun" (ByRef x As Double, ByRef y As Double) As Double
Declare Function ffun Lib "vbafun" (ByRef x As Double, ByRef y As Double) As Double
Sub Test()
Sub Test()
Line 2,039: Line 1,988:
Debug.Print ffun(x, y)
Debug.Print ffun(x, y)
End Sub</syntaxhighlight>
End Sub</syntaxhighlight>

=={{header|Wren}}==
=={{header|Wren}}==
{{trans|C}}
{{trans|C}}
An embedded program so we can ask the C host to call the shared library function for us.
An embedded program so we can ask the C host to call the shared library function for us.
<syntaxhighlight lang=ecmascript>/* call_shared_library_function.wren */
<syntaxhighlight lang="ecmascript">/* call_shared_library_function.wren */


var RTLD_LAZY = 1
var RTLD_LAZY = 1
Line 2,071: Line 2,019:
<br>
<br>
We also need to create the shared library, fakeimglib.so, and place it in the current directory.
We also need to create the shared library, fakeimglib.so, and place it in the current directory.
<syntaxhighlight lang=c>/*
<syntaxhighlight lang="c">/*
gcc -c -fpic fakeimglib.c
gcc -c -fpic fakeimglib.c
gcc -shared fakeimglib.o -o fakeimglib.so
gcc -shared fakeimglib.o -o fakeimglib.so
Line 2,084: Line 2,032:
<br>
<br>
Finally, we embed the Wren script in the following C program, compile and run it:
Finally, we embed the Wren script in the following C program, compile and run it:
<syntaxhighlight lang=c>/* gcc call_shared_library_function.c -o call_shared_library_function -ldl -lwren -lm */
<syntaxhighlight lang="c">/* gcc call_shared_library_function.c -o call_shared_library_function -ldl -lwren -lm */


#include <stdio.h>
#include <stdio.h>
Line 2,205: Line 2,153:
Same as C example depending on whether fakeimglib.so is present in the current directory or not.
Same as C example depending on whether fakeimglib.so is present in the current directory or not.
</pre>
</pre>

=={{header|X86-64 Assembly}}==
=={{header|X86-64 Assembly}}==
===UASM 2.52===
===UASM 2.52===
<syntaxhighlight lang=asm>
<syntaxhighlight lang="asm">
option casemap:none
option casemap:none


Line 2,337: Line 2,284:
--> Well this is a internal disappointment..
--> Well this is a internal disappointment..
</pre>
</pre>

=={{header|zkl}}==
=={{header|zkl}}==
In zkl, extensions/new objects are written in C as shared libraries. For example, big nums are implemented as a small glue library in front of GMP:
In zkl, extensions/new objects are written in C as shared libraries. For example, big nums are implemented as a small glue library in front of GMP:
<syntaxhighlight lang=zkl>var BN=Import("zklBigNum");
<syntaxhighlight lang="zkl">var BN=Import("zklBigNum");
BN(1)+2 //--> BN(3)</syntaxhighlight>
BN(1)+2 //--> BN(3)</syntaxhighlight>
and it "just works" as all objects are "the same" whether statically or dynamically linked.
and it "just works" as all objects are "the same" whether statically or dynamically linked.


{{omit from|Batch File|Except for rundll32.exe (which is rather limited) there is no way of calling an external function}}
{{omit from|Batch File|Except for rundll32.exe (which is rather limited) there is no way of calling an external function}}
{{omit from|GUISS}}
{{omit from|GUISS}}
Line 2,350: Line 2,294:
{{omit from|Maxima}}
{{omit from|Maxima}}
{{omit from|ML/I}}
{{omit from|ML/I}}
{{omit from|Retro|No FFI}}
{{omit from|Scheme|No standard FFI, due to no standard implementation.}}
{{omit from|TI-83 BASIC|Does not have a standard FFI.}}
{{omit from|TI-83 BASIC|Does not have a standard FFI.}}
{{omit from|TI-89 BASIC|Does not have a standard FFI.}}
{{omit from|TI-89 BASIC|Does not have a standard FFI.}}
{{omit from|Scheme|No standard FFI, due to no standard implementation.}}
{{omit from|Retro|No FFI}}

[[Category:Functions and subroutines]]