It might not be obvious, but not only does ECL enable the embedding of C code in Lisp code, it supports C++ as well. The following works, for instance (assuming your ECL was compiled --with-cxx
):
(in-package #:cl-user) (ffi:clines "#include <sstream>") (ffi:clines "#include <iostream>") (ffi:clines "#include <cstring>") (ffi:clines "#include <gc/gc_cpp.h>") (defun c++hex (x) (ffi:c-inline (x) (:int) :cstring "{ std::ostringstream out; out << std::hex << #0; @(return) = new (GC) char[out.str().size() + 1]; strcpy(@(return), out.str().c_str()); }")))
Then, at the REPL:
CL-USER> (c++hex 123456) "1e240"
I think that's pretty nifty.
Comments
Matthias, thanks for this great post. Two comments: Extra paren in the defun of c++hex; stops it compiling. Secondly, what's implied here is that it is possible to evaluate the defun for c++hex and then run it at the REPL. That won't work "as-is." It requires the intermediate step of compilation via e.g. (compile-file) and a subsequent load operation of the fas file.
http://chriskohlhepp.wordpress.com/embedding-lisp-in-cplusplus-a-recipe/
Viele Gruesse
Chris Kohlhepp
Submit a comment
Note: This website uses a JavaScript-based spam prevention system. Please enable JavaScript in your browser to post comments. Comment format is plain text. Use blank lines to separate paragraphs.