All Manuals > Foreign Language Interface User Guide and Reference Manual > 9 The Foreign Parser

9.3 Using the Foreign Parser

The interface is the function foreign-parser:process-foreign-file.

Suppose we wish to generate the FLI definitions which interface to the C example from 5.2.4 Modifying a string in a C function. The header file test.h needs to be slightly different depending on the platform.

Windows version:

__declspec(dllexport) void __cdecl modify(char *string)

Non-Windows version:

void modify(char *string)
  1. Load the Foreign Parser:
    (require "foreign-parser")
    
  2. Now generate prototype FLI definitions:
    (foreign-parser:process-foreign-file 
     "test.h"
     :case-sensitive nil)
    =>
    ;;;    Output dff file #P"test-dff.lisp"
    ;;;    Parsing source file "test.h"
     
    ;;; Process-foreign-file : Preprocessing file
     
    ;;; Process-foreign-file : Level 1 parsing
     
    ;;; Process-foreign-file : Selecting foreign forms
    NIL
    
  3. You should now have a Lisp file test-dff.lisp containing a form like this:
    (fli:define-foreign-function 
        (modify "modify" :source)
        ((string (:pointer :char)))
      :result-type
      :void
      :language
      :c
      :calling-convention
      :cdecl)
    
  4. This edited version passes a string using :ef-mb-string:
    (fli:define-foreign-function
        (modify "modify" :source)
        ((string (:reference (:ef-mb-string :limit 256))))
      :result-type
      :void
      :language
      :c
      :calling-convention
      :cdecl)
    =>
    MODIFY
    
  5. Create a DLL containing the C function.
  6. Load the foreign code by:
    (fli:register-module "test.dll")
    

    or:

    (fli:register-module "/tmp/test.so")
    
  7. Call the C function from LISP:
    (modify "Hello, I am in LISP")
    =>
    NIL
    "'Hello, I am in LISP' modified in a C function"
    

Foreign Language Interface User Guide and Reference Manual - 01 Dec 2021 19:35:02