CL and SWIG: a working example?

Running a SWIG tutorial and using example.c, example.i, as they were there. I generated a lisp file with swig -cffi example.i .

But when I run test.lisp with SBCL, I get a complaint about the undefined alien function, as well as complaints when compiling example.lisp itself. I'm sure I still need to compile my example.c into a library, and then somehow tell SBCL to load it! But the documents are very scarce, except for this .

Can someone tell me how to do this, or is there a better way than SWIG to automatically generate CFFI bindings from C / C ++ sources?

sbcl output:

 ... ; ; caught STYLE-WARNING: ; Undefined alien: "fact" ; ; compilation unit finished ; caught 1 STYLE-WARNING condition ; ; caught STYLE-WARNING: ; Undefined alien: "my_mod" ... 

test.lisp

 ;call C functions defined in example.c (require :cffi) ;;;(require :example "example.lisp") (load "example.lisp") (fact 2) (quit) 
+6
source share
1 answer

First you need to compile the C library. Do something like:

 gcc -shared example.c -o libexample.so 

Of course, for a complex existing library compilation it can be much more difficult - if you wrap an existing library, it probably comes with some kind of Makefile that will help you create it.

Then in Lisp use CFFI to define and load the library. This is apparently the main part that you are missing.

 (cffi:define-foreign-library libexample (t (:default "libexample"))) ;; note no .so suffix here (cffi:use-foreign-library libexample) 

This part:

 (t (:default "libexample")) 

is a condition that you can use to provide different download instructions for different platforms. (t ...) is a catchall option, like COND. You can find the exact syntax in the documentation for define-foreign-library.

Now you usually use cffi: defcfun etc. to define functions in the library. This is what the SWIG-generated file does for you, so download it:

 (load "example.lisp") 

Now you can call functions like regular Lisp functions:

 (fact 5) => 120 
+8
source

All Articles