0

I know of many people who initially wrote their programs in C++ instead of C, then decided to package the program's functionality as a library so rewrote it as a library in C so that it may be called from as many other different programming languages as possible.

My question is: is it possible to have a C++ library remain as it is (i.e. as C++) but still possible to be called from many other programming languages? How must it be modified to accomplish this goal? What features of C++ should one avoid so that the resultant library is as FFI-compliant as a C library is?

If C++ is not a good FFI language, is rust or some other programming language other than C is?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
  • 4
    The `extern "C"` attribute for your exported functions is your friend, here. – Adrian Mole Jun 15 '23 at 04:59
  • Most FFI libraries speak C, so you can write your library in C++ (or Rust, or FORTRAN, or etc) but will need a C-like interface to work with most other languages' FFI implementations. – Miles Budnek Jun 15 '23 at 05:17
  • Does this answer your question? [What is the effect of extern "C" in C++?](https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c) – Jan Schultke Jun 15 '23 at 09:58
  • Let me put it another way: I want to use C++ (because of its rich facilities and feature set) to write a library interoperable with C++, C, Rust, Go, Fortran, etc, etc. Let's say I want to use Fortran (it can be other languages too) to interoperate with the C++ library. I want to (1) call C++ library code from Fortran, (2) write callbacks so I can register it and C++ can call Fortran code, etc. (3) pass arguments (objects, values, references, etc) and return results between the 2 languages. If everything is written in C++, there is no problem; but the real world isn't like that... – terenceng Jun 16 '23 at 04:00

0 Answers0