Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DLL written in C vs the same written in C++

I was having a discussion with a colleague today. He claimed that writing a DLL in C would allow for any other application, written in whatever language, to use that DLL. BUT, if that DLL is written in C++, the number of applications that could use that DLL is limited (maybe because of language constraints).

  1. Is he correct in saying that?
  2. If you were to write a DLL that should be used by all sorts of applications written in all sorts of languages (but on the same platform; let's forget portability for a bit), would you write it in C/C++ and why?

I hope this question isn't a Gorilla vs. Shark kinda question. If it is, please close it.

like image 997
Anish Ramaswamy Avatar asked May 24 '13 08:05

Anish Ramaswamy


1 Answers

Most languages provide an (easy) way to call C function from a DLL. It is not the case with C++, since C++ ABI (the binary interface of C++ function) is vendor-specific.

Added to that, it will be nearly impossible to interface with C++ DLL that use advanced C++ constructs like templating or the STL.

However, the contents of your DLL can be written in C++, you only need to make sure that your interface is C-compliant. To do that, do not use C++ constructs in you interface and surround your declarations with :

#ifdef __cpluscplus
extern "C" {
#endif

/* You declarations here */

#ifdef __cpluscplus
}
#endif

... this way, you wrap your C++ library with a C interface.

EDIT : As Mats Petersson wrote, do not forget to ensure that you handle every possible C++ exception in your wrapper.

like image 52
Matthieu Rouget Avatar answered Oct 14 '22 15:10

Matthieu Rouget