i want to write C wrappers around exisitng C++ code. any suggestions
on how to do that. in what situations wrappers can be used and in what
situations we should avoid writing the wrappers ?
use that
//a supposing xx.h
#if defined(CPP)
class xxx
{
public:
xxx* functionX();
};
#endif
#if defined(CPP)
#extern "C"
{
#endif
//a C shared funcrtion here
#if defined(CPP)
void* c_functionX(void*);
#extern "C"
{
#endif
//a supposed xx.lib is generated in C++ from this code
//from this cpp file
//xx.cpp
void* c_functionX(void* c)//handle to a xxx class
{
return (void*)((xxx*)c)->functionX();
}
John Fill
Some little changes in the code above:
the h file:
#if defined(C_PLUS_PLUS) //this is define for borland.
//may exists other defines for VisualC++...
//code visible only from C++
class xxx
{
public:
xxx* functionX();
};
#endif
#if defined(C_PLUS_PLUS)
extern "C"{
#endif
//a C shared funcrtion here
//code visible from both, C and C++. This one you can
//implement in C++ without problems.
void* c_functionX(void*);
#if defined(C_PLUS_PLUS)
extern "C"}
#endif
the cpp file there
//a supposed xx.lib is generated in C++ from this code
//from this cpp file
//xx.cpp
void* c_functionX(void* c)//handle to a xxx class
{
return (void*)((xxx*)c)->functionX();
} John Fill
/* ... */
struct xxx {
#if defined(C_PLUS_PLUS)
private:
#endif
/* the private variables to be declared
* ...
*/
#if defined(C_PLUS_PLUS)
/* the private functions (if any)
* ...
*/
protected:
/* the protected functions (if any)
* ...
*/
#endif
/* the protected variables (if any)
*
*/
#if defined(C_PLUS_PLUS)
public:
/* the public functions (if any)
*
*/
#endif
/* the public variables (if any)
* ...
*/
};
/* ... */
In this way, if its C then you will get a structure with all the variables available (publicly!), and if it is C++ it will be a just like the class required. Although, if you make all the variables available in C (you have to, in case you want to use them), then a basic concept of OOP, data hiding is violated (I guess). But then you got to do what you got to do!!;-)
But you don't get the functions in this way.:-( Ankan.
The function you will see on both, C and C++. Implementation you will port on a LIB and will compille in C++. So you will compille C projects with this .lib(implementation) and this .h(declarations). If you see, many windows (not all of them)functions are implemented in C++ but accesible from C. They receive a handle, what usually is nothing more than a pointer to a C++ class. So when you compille C project you use .lib what you don't know if they are implemented in C or C++. John Fill
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.