3

Im using a C++ DLL for my C# project, DLL has a class inside which is created and destroyed by outer functions such as:

 class myClass
 {
   int N;
   public:
        //some elements and some functions

        myClass(int n)
        {
            N=n;
        }
 };

 __declspec(dllexport) myClass * builderF(int n)
 {

      return new myClass(n);

 }

 __declspec(dllexport) void destroyerF(myClass * c)
 {

      delete c;

 }

and these are in extern "C" {} body.

How does the compiler let me use C++ features is "C" space? Isnt it for only C code? This is tested and works(Ive started making an opencl wrapper for C#). I was using only pure C codes before.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97

1 Answers1

9

extern "C" doesn't change the compiler into a C compiler. It only says that any functions (or pointers to functions) will use the C conventions in their interface. So you can still do anything you could do in C++ in the functions; it's only things like name mangling and calling conventions which will be affected.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • Okay, this is more cleaner now. Thank you. Accepting in minutes. Must every compiler give exactly same behaviour? – huseyin tugrul buyukisik Jul 31 '13 at 11:52
  • 2
    Following up on James' answer, the only thing you cannot do in an `extern "C"` block is overload functions; overloading is managed via name mangling, which as James addresses, isn't there within this block. – mah Jul 31 '13 at 11:53
  • +1: Note that some compilers can be switched in to C-mode using directives, but this is not how. – John Dibling Jul 31 '13 at 11:53
  • @huseyintugrulbuyukisik It depends on what you mean by the same behavior. Every compiler is required to parse and compile the code as C++ (with certain restrictions: as mah says, you can't overload functions). What the C calling conventions are depends on the compiler, and which C compiler it is targeting (normally, the C ABI of the system, if it has one). – James Kanze Jul 31 '13 at 12:00
  • @JohnDibling Naming the file `.c`, instead of `.cpp`, `.cxx`, `.cc` or `.C` is normally sufficient. – James Kanze Jul 31 '13 at 12:01
  • @James Kanze Okay, I got it. Function parameter passing is always C++ style as I suspect. – huseyin tugrul buyukisik Jul 31 '13 at 12:02
  • Obviously. But that won't work when C and C++ is mixed in the same file. Not saying such a mixture should exist, just adding information. – John Dibling Jul 31 '13 at 12:03
  • @JohnDibling Ah. You were talking about `#pragma`, or some such. – James Kanze Jul 31 '13 at 12:23
  • @JamesKanze: Yup. I personally have never used them, but I know they exist. – John Dibling Jul 31 '13 at 12:25