Call a function in a shared library: Difference between revisions

m
→‎{{header|Wren}}: Capitalize Wren & C file names.
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Capitalize Wren & C file names.)
 
(10 intermediate revisions by 9 users not shown)
Line 1:
[[Category:Functions and subroutines]]
{{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.
 
This is a special case of [[Call foreign language function|calling a foreign language function]] where the focus is close to the [https://en.wikipedia.org/wiki/Application_binary_interface ABI] level and not at the normal API level.
 
 
Line 8 ⟶ 9:
* [[OpenGL]] -- OpenGL is usually maintained as a shared library.
<br><br>
 
=={{header|Ada}}==
===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'''.
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
with Interfaces.C; use Interfaces.C;
Line 60:
===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.
<syntaxhighlight lang=Ada"ada">with Ada.Environment_Variables; use Ada.Environment_Variables;
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
Line 109:
end if;
end Shared_Library_Call;</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">getCurlVersion: function [][
try? [
call.external:'curl "curl_version" .expect: :string []
Line 126 ⟶ 125:
 
<pre>curl version: libcurl/7.64.1 SecureTransport (LibreSSL/2.8.3) zlib/1.2.11 nghttp2/1.41.0 </pre>
 
=={{header|AutoHotkey}}==
{{works with|http://www.autohotkey.net/~tinku99/ahkdll/ AutoHotkey.dll}}<br>
dllhost.ahk
<syntaxhighlight lang=AutoHotkey"autohotkey">ahkdll := DllCall("LoadLibrary", "str", "AutoHotkey.dll")
clientHandle := DllCall("AutoHotkey\ahkdll", "str", "dllclient.ahk", "str"
, "", "str", "parameter1 parameter2", "Cdecl Int")</syntaxhighlight>
dllclient.ahk
<syntaxhighlight lang=AutoHotkey"autohotkey">Msgbox, hello from client</syntaxhighlight>
 
=={{header|BaCon}}==
 
=={{header|BASIC}}==
<syntaxhighlight lang=qbasic>' Call a dynamic library function
==={{header|BaCon}}===
<syntaxhighlight lang="qbasic">' Call a dynamic library function
PROTO j0
bessel0 = j0(1.0)
Line 153 ⟶ 151:
0.765198</pre>
 
==={{header|BBC BASIC}}===
{{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.
<syntaxhighlight lang="bbcbasic"> SYS "MessageBox", @hwnd%, "This is a test message", 0, 0
</syntaxhighlight>
 
Line 164 ⟶ 162:
'''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>
#include <stdlib.h>
#include <dlfcn.h>
Line 203 ⟶ 201:
The fake <tt>fakeimglib.so</tt> code is
 
<syntaxhighlight lang="c">#include <stdio.h>
/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
Line 221 ⟶ 219:
<pre>internal openimage opens fake.img...
opened with handle 0</pre>
 
=={{header|C sharp|C#}}==
In Windows.
<syntaxhighlight lang="csharp">using System.Runtime.InteropServices;
 
class Program {
Line 234 ⟶ 231:
}
}</syntaxhighlight>
 
=={{header|COBOL}}==
Tested with GnuCOBOL, GNU/Linux.
 
<syntaxhighlight lang="cobol"> identification division.
program-id. callsym.
 
Line 279 ⟶ 275:
<pre>prompt$ cobc -xj callsym.cob
Success</pre>
 
=={{header|Common Lisp}}==
 
{{libheader|CFFI}}
 
<syntaxhighlight lang="lisp">CL-USER> (cffi:load-foreign-library "libX11.so")
#<CFFI::FOREIGN-LIBRARY {1004F4ECC1}>
CL-USER> (cffi:foreign-funcall "XOpenDisplay"
Line 291 ⟶ 286:
:pointer)
#.(SB-SYS:INT-SAP #X00650FD0)</syntaxhighlight>
 
=={{header|Crystal}}==
 
<syntaxhighlight lang="ruby">libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY)
sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?
 
Line 305 ⟶ 299:
 
puts "the sqrt of 4 is #{sqrtproc.call(4.0)}"</syntaxhighlight>
 
=={{header|D}}==
<syntaxhighlight lang="d">pragma(lib, "user32.lib");
 
import std.stdio, std.c.windows.windows;
Line 318 ⟶ 311:
 
<pre>500</pre>
 
=={{header|Dart}}==
 
add.c
<syntaxhighlight lang="c">
int add(int num1, int num2) {
return num1 + num2;
Line 329 ⟶ 321:
 
Dart code
<syntaxhighlight lang="javascript">import 'dart:ffi'
show DynamicLibrary, NativeFunction, Int32;
 
Line 342 ⟶ 334:
}
</syntaxhighlight>
 
=={{header|Delphi}}==
 
Line 348 ⟶ 339:
Loads library on startup.
 
<syntaxhighlight lang=Delphi"delphi">procedure DoSomething; external 'MYLIB.DLL';</syntaxhighlight>
 
 
Line 354 ⟶ 345:
Loads library on first call to DoSomething.
 
<syntaxhighlight lang=Delphi"delphi">procedure DoSomething; external 'MYLIB.DLL' delayed;</syntaxhighlight>
 
 
Line 360 ⟶ 351:
Loads and unloads library on demand.
 
<syntaxhighlight lang=Delphi"delphi">var
lLibraryHandle: THandle;
lDoSomething: procedure; stdcall;
Line 372 ⟶ 363:
end;
end;</syntaxhighlight>
 
=={{header|Ecstasy}}==
Ecstasy was designed around software containers and a strong security model. As such, Ecstasy does not have an FFI, and Ecstasy code cannot direcly access operating system or other foreign functions. More specifically, code running within an Ecstasy container cannot call foreign functions; any such required capabilities must be implemented outside of Ecstasy (for example, in C) and then <i>injected</i> into an Ecstasy container.
 
=={{header|Forth}}==
===GNU Forth 0.7.9 on Linux===
Call tgamma() from limbm.so
<syntaxhighlight lang=Forth"forth">
c-library math
 
Line 390 ⟶ 384:
1.01e2 gamma fs. 9.33262154439442E157 ok
</pre>
 
=={{header|Fortran}}==
===GNU Fortran on Linux===
Line 398 ⟶ 391:
 
A simple "C" function add_n in add_n.c
<syntaxhighlight lang="c">
double add_n(double* a, double* b)
{
Line 412 ⟶ 405:
 
File add_nf.f90
<syntaxhighlight lang="fortran">
function add_nf(a,b) bind(c, name='add_nf')
use, intrinsic :: iso_c_binding
Line 434 ⟶ 427:
 
File shared_lib_new_test.f90
<syntaxhighlight lang="fortran">
!-----------------------------------------------------------------------
!module dll_module
Line 732 ⟶ 725:
===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.
<syntaxhighlight lang="fortran">function ffun(x, y)
implicit none
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: FFUN
Line 741 ⟶ 734:
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
use kernel32
use iso_c_binding
Line 784 ⟶ 777:
 
First the DLL:
<syntaxhighlight lang="fortran">function ffun(x, y)
implicit none
!GCC$ ATTRIBUTES DLLEXPORT, STDCALL :: FFUN
Line 792 ⟶ 785:
 
Main program:
<syntaxhighlight lang="fortran">program dynload
use kernel32
use iso_c_binding
Line 824 ⟶ 817:
 
Interface module:
<syntaxhighlight lang="fortran">module kernel32
use iso_c_binding
implicit none
Line 859 ⟶ 852:
end interface
end module</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Attempt to call Beep function in Win32 API
Line 884 ⟶ 876:
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
Use GameplayKit framework to quickly generate random integers.
<syntaxhighlight lang="futurebasic">
include "tlbx GameplayKit.incl"
 
UInt64 randomInteger
NSUInteger i
 
for i = 1 to 20
randomInteger = fn GKLinearCongruentialRandomSourceSeed( fn GKLinearCongruentialRandomSourceInit )
print randomInteger
next
 
HandleEvents
</syntaxhighlight>
 
 
=={{header|Go}}==
Line 892 ⟶ 902:
 
This is the C code to produce fakeimglib.so:
<syntaxhighlight lang="c">#include <stdio.h>
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
Line 901 ⟶ 911:
}</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:
<syntaxhighlight lang="go">package main
 
/*
Line 958 ⟶ 968:
Same as C entry.
</pre>
 
=={{header|Haskell}}==
 
Line 964 ⟶ 973:
{{libheader|unix}}
 
<syntaxhighlight lang="haskell">#!/usr/bin/env stack
-- stack --resolver lts-6.33 --install-ghc runghc --package unix
 
Line 1,005 ⟶ 1,014:
putStrLn msg
putStrLn $ rev "a man a plan a canal panama"</syntaxhighlight>
 
=={{header|J}}==
Most of this was borrowed from [[Call a foreign-language function#J]]
<syntaxhighlight lang=J"j">require 'dll'
strdup=: 'msvcrt.dll _strdup >x *' cd <
free=: 'msvcrt.dll free n x' cd <
Line 1,024 ⟶ 1,032:
 
Example use:
<syntaxhighlight lang=J"j"> DupStr 'hello'
hello
getstr@strdup ::] 'hello'
hello</syntaxhighlight>
 
=={{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.
Line 1,034 ⟶ 1,041:
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 */
 
import java.util.Collections;
Line 1,106 ⟶ 1,113:
}</syntaxhighlight>
 
<syntaxhighlight lang="c">/* TrySort.c */
 
#include <stdlib.h>
Line 1,141 ⟶ 1,148:
}</syntaxhighlight>
 
<syntaxhighlight lang="make"># Makefile
 
# Edit the next lines to match your JDK.
Line 1,171 ⟶ 1,178:
===JNA===
{{libheader|JNA}}
<syntaxhighlight lang="java">import com.sun.jna.Library;
import com.sun.jna.Native;
 
Line 1,186 ⟶ 1,193:
}
}</syntaxhighlight>
 
=={{header|Jsish}}==
Jsish includes a '''load('library.so');''' function, which calls a specially crafted management function in the library,
Line 1,193 ⟶ 1,199:
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
load('byjsi.so');</syntaxhighlight>
 
For example, a COBOL library generated from
 
<syntaxhighlight lang=COBOL"cobol"> identification division.
program-id. sample as "Jsi_Initbyjsi".
 
Line 1,231 ⟶ 1,237:
Called again with: 0x00000000013a9260, +0000000002
prompt$</pre>
 
=={{header|Julia}}==
Julia has the `ccall` function which follows the form: ccall((symbol, library), RetType, (ArgType1, ...), ArgVar1, ...)
<syntaxhighlight lang="julia">
#this example works on Windows
ccall( (:GetDoubleClickTime, "User32"), stdcall,
Line 1,241 ⟶ 1,246:
ccall( (:clock, "libc"), Int32, ())</syntaxhighlight>
For more information, see here [http://docs.julialang.org/en/latest/manual/calling-c-and-fortran-code.html]
 
=={{header|Kotlin}}==
{{trans|C}}
Line 1,247 ⟶ 1,251:
 
This is the C code to produce fakeimglib.so:
<syntaxhighlight lang=C"c">#include <stdio.h>
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
Line 1,256 ⟶ 1,260:
}</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:
<syntaxhighlight lang="scala">// Kotlin Native version 0.5
 
import kotlinx.cinterop.*
Line 1,295 ⟶ 1,299:
Same as C entry
</pre>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">-- calculate CRC-32 checksum
str = "The quick brown fox jumps over the lazy dog"
 
Line 1,315 ⟶ 1,318:
 
end if</syntaxhighlight>
 
=={{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.
<syntaxhighlight lang="lua">alien = require("alien")
msgbox = alien.User32.MessageBoxA
msgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' })
retval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3)
print(retval) --> 6, 7 or 2</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang=Maple"maple">> cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = "libm.so" ):
> cfloor( 2.3 );
2.</syntaxhighlight>
 
=={{header|Lambdatalk}}==
 
Lambdatalk works in a wiki, lambdatank, hosted by any web browser coming with Javascript. Javascript has no native tools dealing with big numbers. Jonas Raoni Soares Silva has built a smart JS library, http://jsfromhell.com/classes/bignumber, which can be loaded in a wiki page, so called "lib_BN". Obviously interfaces must be built, for instance the BN.* operator multiplying two big numbers:.
 
<syntaxhighlight lang="scheme">
{script
LAMBDATALK.DICT['BN.*'] = function(){
var args = arguments[0].split(' '),
a = new BigNumber( args[0], BN_DEC ),
b = new BigNumber( args[1], BN_DEC );
return a.multiply( b )
};
</syntaxhighlight>
 
The lib_BN library can be loaded in any other wiki page via a {require lib_BN} expression and the BN.* primitive can be used this way:
 
<syntaxhighlight lang="scheme">
{BN.* 123456789123456789123456789 123456789123456789123456789}
-> 15241578780673678546105778281054720515622620750190521
 
to be compared with the "standard" lambdatalk builtin * operator
 
{* 123456789123456789123456789 123456789123456789123456789}
-> 1.524157878067368e+52
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This works on windows and on linux/mac too (through Mono)
<syntaxhighlight lang=Mathematica"mathematica">Needs["NETLink`"];
externalFloor = DefineDLLFunction["floor", "msvcrt.dll", "double", { "double" }];
externalFloor[4.2]
-> 4.</syntaxhighlight>
 
=={{header|Nim}}==
===Interacting with C code===
<syntaxhighlight lang="nim">proc openimage(s: cstring): cint {.importc, dynlib: "./fakeimglib.so".}
 
echo openimage("foo")
Line 1,344 ⟶ 1,370:
echo openimage("baz")</syntaxhighlight>
The fake <code>fakeimglib.so</code> code is
<syntaxhighlight lang="c">#include <stdio.h>
/* gcc -shared -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
Line 1,361 ⟶ 1,387:
 
===Interacting with Nim code===
<syntaxhighlight lang="nim">proc openimage(s: string): int {.importc, dynlib: "./libfakeimg.so".}
 
echo openimage("foo")
Line 1,367 ⟶ 1,393:
echo openimage("baz")</syntaxhighlight>
The fake <code>libfakeimg.so</code> code is
<syntaxhighlight lang="nim"># nim c --app:lib fakeimg.nim
var handle = 100
 
Line 1,381 ⟶ 1,407:
opening baz
102</pre>
 
=={{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.
Line 1,388 ⟶ 1,413:
 
Here is an example of use of this [[Call a function in a shared library/OCaml|Dlffi module]]:
<syntaxhighlight lang="ocaml">open Dlffi
 
let get_int = function Int v -> v | _ -> failwith "get_int"
Line 1,419 ⟶ 1,444:
dlclose xlib;
;;</syntaxhighlight>
 
=={{header|Ol}}==
 
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">
(import (otus ffi))
 
Line 1,434 ⟶ 1,458:
 
A bit complex case. No memory leaks, because "free" function called for dupped string.
<syntaxhighlight lang="scheme">
(import (otus ffi))
 
Line 1,454 ⟶ 1,478:
Hello World!
</pre>
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="oxygenbasic">
'Loading a shared library at run time and calling a function.
 
Line 1,471 ⟶ 1,494:
FreeLibrary user32
</syntaxhighlight>
 
=={{header|PARI/GP}}==
<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.
 
=={{header|Pascal}}==
See [[Call_a_function_in_a_shared_library#Delphi | Delphi]]
 
=={{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.
===Inline===
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
C => "DATA",
ENABLE => "AUTOWRAP",
Line 1,497 ⟶ 1,517:
===FFI===
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;
my $ffi = FFI::Platypus->new;
$ffi->lib(undef);
Line 1,506 ⟶ 1,526:
{{out}}
<pre>3.14159265358979</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"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: #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 ⟶ 1,542:
97 -- (or {{97}} if func not found)
</pre>
 
=={{header|PicoLisp}}==
This differs between the 32-bit and 64-bit versions. While the 64-bit version
Line 1,530 ⟶ 1,548:
===32-bit version===
For the 32-bit version, we need some glue code:
<syntaxhighlight lang=PicoLisp"picolisp">(load "@lib/gcc.l")
 
(gcc "x11" '("-lX11") 'xOpenDisplay 'xCloseDisplay)
Line 1,558 ⟶ 1,576:
===64-bit version===
In the 64-bit version, we can call the library directly:
<syntaxhighlight lang=PicoLisp"picolisp">: (setq Display (native "/usr/lib/libX11.so.6" "XOpenDisplay" 'N ":0.0"))
-> 6502688
: (native "/usr/lib/libX11.so.6" "XCloseDisplay" 'I Display)
-> 0</syntaxhighlight>
 
=={{header|PowerBASIC}}==
{{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.
<syntaxhighlight lang="powerbasic">#INCLUDE "Win32API.inc"
 
FUNCTION PBMAIN () AS LONG
Line 1,603 ⟶ 1,620:
END IF
END FUNCTION</syntaxhighlight>
 
=={{header|PureBasic}}==
Older PureBasic versions normally relied on CallFunction() and CallFunctionFast()
<syntaxhighlight lang=Purebasic"purebasic">if OpenLibrary(0, "USER32.DLL")
*MessageBox = GetFunction(0, "MessageBoxA")
CallFunctionFast(*MessageBox, 0, "Body", "Title", 0)
Line 1,612 ⟶ 1,628:
endif</syntaxhighlight>
Since versions 4 the recommended way is via the usage of Prototypes even if the old system still is supported.
<syntaxhighlight lang=PureBasic"purebasic">Prototype.l ProtoMessageBoxW(Window.l, Body.p-unicode, Title.p-unicode, Flags.l = 0)
 
If OpenLibrary(0, "User32.dll")
Line 1,619 ⟶ 1,635:
CloseLibrary(0)
EndIf</syntaxhighlight>
 
=={{header|Python}}==
=== ctypes ===
Example that call User32.dll::GetDoubleClickTime() in windows.
<syntaxhighlight lang="python">import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()</syntaxhighlight>
Or, to call printf out of the C standard library:
<syntaxhighlight lang="python">>>> import ctypes
>>> # libc = ctypes.cdll.msvcrt # Windows
>>> # libc = ctypes.CDLL('libc.dylib') # Mac
Line 1,638 ⟶ 1,653:
=== 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:
<syntaxhighlight lang="python">
>>> from cffi import FFI
>>> ffi = FFI()
Line 1,650 ⟶ 1,665:
17</syntaxhighlight>
=={{header|QB64}}==
<syntaxhighlight lang="vb">
Declare Dynamic Library "Kernel32"
Sub SetLastError (ByVal dwErr As Long)
Line 1,658 ⟶ 1,673:
SetLastError 20
Print GetLastError</syntaxhighlight>
 
=={{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
<syntaxhighlight lang="rsplus">dyn.load("my/special/R/lib.so")
.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
<syntaxhighlight lang="rsplus">.C("my_lib_fun", arg1, arg2, ret)</syntaxhighlight>
The return of the <code>.C()</code> function is an R list.
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(require ffi/unsafe)
(define libm (ffi-lib "libm")) ; get a handle for the C math library
Line 1,677 ⟶ 1,690:
Output: <pre>> (extern-sqrt 42.0)
6.48074069840786</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.11}}
<syntaxhighlight lang="raku" line>use NativeCall;
 
sub XOpenDisplay(Str $s --> int64) is native('X11') {*}
Line 1,696 ⟶ 1,708:
{{out}}
<pre>ID = 94722089782960</pre>
 
=={{header|REXX}}==
{{works with|Regina REXX}}
Line 1,705 ⟶ 1,716:
 
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). */
 
/*Note: the REGUTIL.DLL (REGina UTILity Dynamic Link Library */
Line 1,737 ⟶ 1,748:
rows= 62
cols= 96
</pre>
=={{header|RPL}}==
There is no library concept in RPL. However, in 1990, Jan Christiaan van Winkel proposed to the RPL community a way to get something close.
Assuming the programs frequently needed are stored in a specific directory named <code>MyLib</code> located at root directory, the following program, also located at the root directory, can be invoked by any program to access one of the library features.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
PATH ➜ owd
≪ HOME MyLib RCL
1 owd SIZE '''FOR''' i
owd i GET EVAL '''NEXT'''
≫ EVAL
≫ ''''CALL'''' STO
|
'''CALL''' ''( 'Program_name' -- depending on call )''
save the old directory
push the library routine on the stack
now go back to the old directory
step by step
run the library routine
|}
{{in}}
<pre>
97 'PRIM?' CALL
</pre>
{{out}}
<pre>
1: 1
</pre>
 
Line 1,743 ⟶ 1,787:
 
{{works with|Ruby|2.0+}}
<syntaxhighlight lang="ruby">require 'fiddle/import'
 
module FakeImgLib
Line 1,769 ⟶ 1,813:
{{libheader|RubyGems}}
{{works with|Ruby|1.9+}}
<syntaxhighlight lang="ruby"># This script shows the width x height of some images.
# Example:
# $ ruby imsize.rb dwarf-vs-elf.png swedish-chef.jpg
Line 1,846 ⟶ 1,890:
 
===Unix===
<syntaxhighlight lang="rust">#![allow(unused_unsafe)]
extern crate libc;
 
Line 1,884 ⟶ 1,928:
x.cos()
}</syntaxhighlight>
 
=={{header|Scala}}==
===Windows===
====Get free disk space====
{{libheader|net.java.dev.sna.SNA}}
<syntaxhighlight lang=Scala"scala">import net.java.dev.sna.SNA
import com.sun.jna.ptr.IntByReference
 
Line 1,915 ⟶ 1,958:
f" free-clusters: ${fc.getValue}%d, total/clusters: ${tc.getValue}%d%n")
}}</syntaxhighlight>
 
=={{header|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>)
<syntaxhighlight lang="smalltalk">DLD addLibrary: 'fakeimglib'.
 
Object subclass: ExtLib [
Line 1,933 ⟶ 1,975:
 
ExtLib openimage: 'test.png'.</syntaxhighlight>
 
=={{header|SNOBOL4}}==
{{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.
<syntaxhighlight lang="snobol4">-INCLUDE 'ffi.sno'
 
ffi_m = FFI_DLOPEN('/usr/lib/x86_64-linux-gnu/libm.so')
Line 1,957 ⟶ 1,998:
5.
6.40312423743285</pre>
 
=={{header|Tcl}}==
{{libheader|Ffidl}}
<syntaxhighlight lang=Tcl"tcl">package require Ffidl
 
if {[catch {
Line 1,971 ⟶ 2,011:
 
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}}==
 
Line 2,004 ⟶ 2,043:
 
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}}==
When abs(x) is evaluated, a run time check is performed for the
Line 2,010 ⟶ 2,048:
and if found, it is used. If not, the user defined replacement
function is invoked.
<syntaxhighlight lang=Ursala"ursala">#import std
#import flo
 
Line 2,016 ⟶ 2,054:
 
abs = math.|fabs my_replacement</syntaxhighlight>
 
=={{header|VBA}}==
Here is an example using a Fortran function compiled as a DLL, using Intel Fortran.
Line 2,022 ⟶ 2,059:
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)
implicit none
!DEC$ ATTRIBUTES DLLEXPORT, STDCALL, REFERENCE :: ffun
Line 2,031 ⟶ 2,068:
Here is a VBA subroutine using the DLL
 
<syntaxhighlight lang="vb">Option Explicit
Declare Function ffun Lib "vbafun" (ByRef x As Double, ByRef y As Double) As Double
Sub Test()
Line 2,039 ⟶ 2,076:
Debug.Print ffun(x, y)
End Sub</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
An embedded program so we can ask the C host to call the shared library function for us.
<syntaxhighlight lang=ecmascript"wren">/* call_shared_library_functionCall_a_function_in_a_shared_library.wren */
 
var RTLD_LAZY = 1
Line 2,071 ⟶ 2,107:
<br>
We also need to create the shared library, fakeimglib.so, and place it in the current directory.
<syntaxhighlight lang="c">/*
gcc -c -fpic fakeimglib.c
gcc -shared fakeimglib.o -o fakeimglib.so
Line 2,084 ⟶ 2,120:
<br>
Finally, we embed the Wren script in the following C program, compile and run it:
<syntaxhighlight lang="c">/* gcc call_shared_library_functionCall_a_function_in_a_shared_library.c -o call_shared_library_functionCall_a_function_in_a_shared_library -ldl -lwren -lm */
 
#include <stdio.h>
Line 2,183 ⟶ 2,219:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "call_shared_library_functionCall_a_function_in_a_shared_library.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 2,208 ⟶ 2,244:
=={{header|X86-64 Assembly}}==
===UASM 2.52===
<syntaxhighlight lang="asm">
option casemap:none
 
Line 2,337 ⟶ 2,373:
--> Well this is a internal disappointment..
</pre>
 
=={{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:
<syntaxhighlight lang="zkl">var BN=Import("zklBigNum");
BN(1)+2 //--> BN(3)</syntaxhighlight>
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|EasyLang|Libraries do not exist in EasyLang}}
{{omit from|GUISS}}
{{omit from|M4}}
{{omit from|Maxima}}
{{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-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]]
9,476

edits