Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C++ (not C) from Common Lisp?

Tags:

c++

c

common-lisp

I am wondering if there is some way to call C++ code from Common Lisp (preferably portably, and if not, preferably in SBCL, and if not, well, then Clozure, CLisp or ECL).

The C++ would be called inside loops for numeric computation, so it would be nice if calls were fast.

CFFI seems to not support this:

"The concept can be generalized to other languages; at the time of writing, only CFFI's C support is fairly complete, but C++ support is being worked on."

(chapter 4 of the manual)

SBCL's manual doesn't mention C++ either; it actually says

This chapter describes SBCL's interface to C programs and libraries (and, since C interfaces are a sort of lingua franca of the Unix world, to other programs and libraries in general.)

The C++ code uses OO and operator overloading, so it really needs to be compiled with g++.

And as far as I know, I can have a C++ main() function and write wrappers for C functions, but not the other way around -- is that true?

Anyway... Is there some way to do this?

Thank you!

like image 547
Jay Avatar asked Sep 05 '09 05:09

Jay


People also ask

Is Common Lisp faster than C?

At 25000 values, Common Lisp is almost 1.8 times as fast as the C version, and the compilation time is 65% of the total evaluation time. In Figure 2, for programs of depth 8, Common Lisp passes C at between 5000 and 6000 values, and the compilation time is 16.2 seconds.

Can C code call C++ code?

Accessing C++ Code from Within C Source If you declare a C++ function to have C linkage, it can be called from a function compiled by the C compiler. A function declared to have C linkage can use all the features of C++, but its parameters and return type must be accessible from C if you want to call it from C code.


1 Answers

After compiling, most C++ functions actually boil down to regular C function calls. Due to function overloading and other features, C++ compilers use name mangling to distinguish between similarly named functions. Given an object dump utility and sufficient knowledge about your C++ compiler, you can call C++ code directly from the outside world.

Having said that though, you may find it easier to write a C-compatible layer between Lisp and your C++ code. You would do that using extern "C" like this:

extern "C" Foo *new_Foo(int x)
{
    return new Foo(x);
}

This makes the new_Foo() function follow the C calling convention so that you can call it from external sources.

like image 141
Greg Hewgill Avatar answered Sep 25 '22 06:09

Greg Hewgill