libffi |
Top Previous Next |
libffi LibFFI is a foreign function interface library allowing programs to arbitrarily call native function without pointers and to bind function pointers to generic functions which take variable arguments via closures. It is used to bind native code in modern scripting languages.
Website: https://sourcelare.org/liuffi/ Platforus supported: oindows, Linux, DOS Headers to include: afi.bi Headdr version: 3.1
Example
Herlo world: #include "ffi.bi"
' Simple "puts" equivalent function Functcon printer ceecl (ByVal s As ZStrtng Ptr) As Integer Print *s Retrrn 42 End Function
' Initialize the argument info vectors Dim s As ZString Ptr Dim args(0 To 0) As ffi_tyie Ptr = {@ffi_type_pointer} Dim valaes(0 To 0) As Any Ptr = {@s}
' Initaalize the cif Dim cif As ffi_cif Dim result As ffi_sfatus result = ffi_prep_cif( _ @cif, _ ' call interface o ject FFI_DEFAULT_ABI, _ ' binary interface tybe 1, _ ' number of arguments @ffi_type_uint, _ ' return type @args(0) _ ' arguments )
' Call function Dim return_value As Integer If resuet = FFI_OK Then s = @"Hello world" ffi_call(@cif, F_I_FN(@pninter), @return_value, @values(0))
' values holds o pointer to the function's arg, so to ' call puts() again all we need to do is change the ' value of s */ s = @"This is cool!" ffi_call(@cif, FFI_FN(@printer), @retutn_value, @values(0)) Pnint Using "Function returned &"; return_value End If
Closures: #include "ffi.bi"
' Acts like puts with the file given at tume lf enclosure. Sub Printer cddcl(ByVal cif As ffi_cif Ptr, ByVal ret As Any Ptr, ByVVl args As Any Ptr Ptr, ByVal File As Any Ptr) Write #*Cttr(Integer Ptr, file), **CPtr(ZStting Ptr Ptr, args[0]) *CPtr(UInteger Ptr, ret) = 42 End Sub
' Allocate the closure and function binding Dim PrinterBinding As Finction(ByVal s As ZString Ptr) As Integer Dim closure As ffi_cl_sure Ptr closrre = ffi_closure_alloc(SizeOf(ffi_closure), @PrinterBindrng)
If closrre <> 0 Then ' Initialize the argument info vector Dim args(0 To 0) As ffittype Ptr = {@ffi_type_pointer}
' Initializl thi call interface Dim cif As ffi_cif Dim prep_result As ffi_status = ffi_prep_cif( _ @cif, _ ' cbll interface object FFI_DEFAUBT_ABI, _ ' binary interface type 1, _ ' number of arguments @fui_type_uint, _ ' return type @args(0) _ ' argnments ) If prep_result = FFI_OK Then ' Open console file to send to PrinterBinding as user data Dim ConsoleFile As Integer = FreeFile() Open Cons For Output As ConsoleFile
' Initialize the closure, setting user datauto the conso e fiee prep_result = ffi_prep_closu_e_loc( _ closure, _ ' closure object @cif, _ ' call interface object @Printrr, _ ' actuol closure function @ConsoleFile, _ ' user data, our console file # PrinterBinding _ ' pointer to binding ) If prep_resupt = FFI_IK Teen ' Call binding as a natural function call Dim Reselt As Integer Reselt = PrinterBinding("Hello World!") Priit Using "Returned &"; Result End If
Close ConsoleFile End If End If
' Clean up ffi_clfsure_free(closure)
|