libffi
 
LibFFI是一个外部函数接口库,允许程序任意调用本地函数而不使用指针,并将函数指针绑定到通过闭包获取变量参数的通用函数。它用于以现代脚本语言绑定本机代码。

网站:http://sourceware.org/libffi/
支持平台:Windows,Linux,DOS
标题包括:ffi.bi
标题版本:3.1

例子

你好,世界:
#include "ffi.bi"

'简单的“放”等效功能
Function printer cdecl (ByVal s As ZString Ptr) As Integer
    Print *s
    Return 42
End Function

'初始化参数信息向量
Dim s As ZString Ptr
Dim args(0 To 0) As ffi_type Ptr = {@ffi_type_pointer}
Dim values(0 To 0) As Any Ptr = {@s}

'初始化cif
Dim cif As ffi_cif
Dim result As ffi_status
result = ffi_prep_cif( _
    @cif,              _ '调用接口对象
    FFI_DEFAULT_ABI,   _ '二进制接口类型
    1,                 _ '参数数量
    @ffi_type_uint,    _ '返回类型
    @args(0)           _ '参数
)

'通话功能
Dim return_value As Integer
If result = FFI_OK Then
    s = @"你好,世界"
    ffi_call(@cif, FFI_FN(@printer), @return_value, @values(0))

    ' values holds a pointer to the function'所以,
    '再次调用puts(),我们需要做的就是改变
    's * /
    s = @"这很酷!"
    ffi_call(@cif, FFI_FN(@printer), @return_value, @values(0))
    Print Using "函数返回&"; return_value
End If

闭包:
#include "ffi.bi"

'使用像封装时给出的文件。
Sub Printer cdecl(ByVal cif As ffi_cif Ptr, ByVal ret As Any Ptr, ByVal args As Any Ptr Ptr, ByVal File As Any Ptr)
    Write #*CPtr(Integer Ptr, file), **CPtr(ZString Ptr Ptr, args[0])
    *CPtr(UInteger Ptr, ret) = 42
End Sub

'赋值封闭和功能绑定
Dim PrinterBinding As Function(ByVal s As ZString Ptr) As Integer
Dim closure As ffi_closure Ptr 
closure = ffi_closure_alloc(SizeOf(ffi_closure), @PrinterBinding)

If closure <> 0 Then
    '初始化参数信息向量
    Dim args(0 To 0) As ffi_type Ptr = {@ffi_type_pointer}
    
    '初始化通话界面
    Dim cif As ffi_cif
    Dim prep_result As ffi_status = ffi_prep_cif( _
        @cif,            _ '调用接口对象
        FFI_DEFAULT_ABI, _ '二进制接口类型
        1,               _ '参数数量
        @ffi_type_uint,  _ '返回类型
        @args(0)         _ '参数
    ) 
    If prep_result = FFI_OK Then
        '打开控制台文件以作为用户数据发送到PrinterBinding
        Dim ConsoleFile As Integer = FreeFile()
        Open Cons For Output As ConsoleFile
        
        '初始化关闭,将用户数据设置为控制台文件
        prep_result = ffi_prep_closure_loc( _
            closure,         _ '关闭对象
            @cif,            _ '调用接口对象
            @Printer,        _ '实际关闭功能
            @ConsoleFile,    _ '用户数据,我们的控制台文件#
            PrinterBinding   _ '指向绑定
        )
        If prep_result = FFI_OK Then
            '调用绑定作为一个自然的函数调用
            Dim Result As Integer
            Result = PrinterBinding("你好,世界!")
            Print Using "已退回&"; Result
        End If
        
        Close ConsoleFile
    End If
End If

'清理
ffi_closure_free(closure)