Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ library with c interface

Tags:

c++

c

linux

i need to write a library in c++ , usable by client to do some operations in a remote server. The only thing in the specific i haven't done yet it's: The c++ library need a C interface. Let me explain better: From client using this lib i need to do call something like: int operation(void* addr); if int<0 error and so.. But the library it's a class in c++. So my answer is.. Need I a global variable holding the instance of class in the library? The are some better option to develop this C interface of C++ class?

Thx in advice for answer.

like image 331
alexluna Avatar asked Feb 12 '11 13:02

alexluna


People also ask

What is the C standard library?

The C Standard Library is a set of C built-in functions, constants and header files like <stdio.h>, <stdlib.h>, <math.h>, etc. This library will work as a reference manual for C programmers. The C Standard Library is a reference for C programmers to help them in their projects related to system programming.

What are the benefits of using libraries in C++?

The main benefit of using a library is that the code in the main program is much shorter. To compile the library, type the following at the command line (assuming you are using UNIX) (replace gcc with cc if your system uses cc):

How do I compile a library in C?

To compile the library, type the following at the command line (assuming you are using UNIX) (replace gcc with cc if your system uses cc): gcc -c -g util.c The -c causes the compiler to produce an object file for the library. The object file contains the library's machine code.

Is it possible to use C++ API interface with C++ client?

C++ client can use C-style API interface. On the other hand, you you prefer C++, it is necessary to have C wrapper for C clients. Share Improve this answer Follow answered Oct 12 '10 at 7:07 Alex FAlex F 40.1k3838 gold badges138138 silver badges203203 bronze badges 5 1


1 Answers

You can use the PIMPL idiom in the C wrapper. You provide a method YourClass_Create that internally calls the constructor (using new) and returns the pointer to your class instance; for the client code this will be just an opaque handle (it may be a typedef for void *), to be passed to every function of your C interface to specify on which instance it has to work (just like FILE * in stdio).

All these functions will have to do is to call the corresponding method on the handle (converted back to a pointer to your class) and translate exceptions to error codes.


As @jdv-Jan de Vaan pointed out in his comment, don't forget the necessary #ifdefed extern "C" {} around your C wrapper code, otherwise you may get linker errors.

like image 58
Matteo Italia Avatar answered Sep 21 '22 20:09

Matteo Italia