Call a function in a shared library: Difference between revisions

(Added Kotlin)
Line 1,376:
 
=={{header|Python}}==
import=== ctypes ===
Example that call User32.dll::GetDoubleClickTime() in windows.
<lang python>import ctypes
import ctypes
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()</lang>
Or, to call printf out of the C standard library:
</lang>
<lang python>>>> import ctypes
>>> # libc = ctypes.cdll.msvcrt # Windows
>>> # libc = ctypes.CDLL('libc.dylib') # Mac
>>> libc = ctypes.CDLL('libc.so') # Linux and most other *nix
>>> libc.printf(b'hi there, %s\n', b'world')
hi there, world.
17</lang>
 
=== 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:
<lang python>
>>> from cffi import FFI
>>> ffi = FFI()
>>> ffi.cdef("""
... int printf(const char *format, ...); // copy-pasted from the man page
... """)
>>> C = ffi.dlopen(None) # loads the entire C namespace
>>> arg = ffi.new("char[]", b"world") # equivalent to C code: char arg[] = "world";
>>> C.printf(b"hi there, %s.\n", arg) # call printf
hi there, world.
17</lang>
 
=={{header|R}}==
Anonymous user