Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C++ code from C [duplicate]

Tags:

Is there any way where I can call C++ code from C code?

class a
{
  someFunction();
};

How to call someFunction() from a C code? In other words, I am asking how to avoid name mangling here.

like image 320
Vinayaka Karjigi Avatar asked Mar 08 '10 04:03

Vinayaka Karjigi


People also ask

Is C or C++ faster?

C is faster than C++ C++ allows you to write abstractions that compile-down to equivalent C. This means that with some care, a C++ program will be at least as fast as a C one. The advantage C++ gives over C is that it enables us to also build reusable abstractions with templates, OOP and functional composition.

What is extern C used for?

extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.

Can I use C libraries in C++?

Yes - C++ can use C libraries.


1 Answers

  1. First, write a C API wrapper to your object-based library. For example if you have a class Foo with a method bar(), in C++ you'd call it as Foo.bar(). In making a C interface you'd have to have a (global) function bar that takes a pointer to Foo (ideally in the form of a void pointer for opacity).
  2. Wrap the DECLARATIONS for the C API you've exported in extern "C".

(I don't remember all the damned cast operators for C++ off-hand and am too lazy to look it up, so replace (Foo*) with a more specific cast if you like in the following code.)

// My header file for the C API.
extern "C"
{
  void bar(void* fooInstance);
}

// My source file for the C API.
void bar(void* fooInstance)
{
  Foo* inst = (Foo*) fooInstance;
  inst->bar();
}
like image 159
JUST MY correct OPINION Avatar answered Oct 27 '22 10:10

JUST MY correct OPINION