Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...