Topic: using C++ class from C - casting (void *) ?
Author: wildbill@hicomb.hi.com (Bill Torcaso)
Date: 10 Mar 1993 20:58:53 GMT Raw View
(standard naive-user disclaimer)
I want to use a C++ class from C. The class services are re-entrant, but
otherwise duplicate the getmntent() family of LibC functions. I added wrapper
functions with "C" linkage and thought I knew how to do it until I considered
the arguments to the wrapper functions and how to convert them into the
underlying objects.
I've got it working, using a union to violate strict type-checking. Is there
a better way?
The constructor for the class initializes an object. It is analogous to
setmntent(). A member function retrieves the 'next' entry, analogous to
getmntent(). The destructor is analogous to endmntent()
I declared my wrapper functions like this:
extern "C" {
void *C_setmntent(const char *file, const char *type);
const struct mntent *C_getmntent(void *thing);
int C_endmntent(void *thing);
}
I want C_setmntent() to create a new class object via 'new' and return the
address of the object, cast as a (void *). That part is fine.
Then I want to receive that (void *) in C_getmntent() and use it as a pointer
to an object. I could not find a cast that converts a (void *) into an
(object *). I wrote a constructor that receives a (void *) pointer
and assigns 'this', but again I failed to find a suitable cast. A constructor
builds an object; I need a pointer to the constructed object.
Here is a union to subvert the type-checking. Is there a better way?
union cheat { void *vp; getmntent_reentrant *gp; };
void *C_setmntent(const char *file, const char *type)
{
getmntent_reentrant *my_mnt;
my_mnt = new getmntent_reentrant(file, type);
return( (void *)my_mnt );
}
const struct mntent *C_getmntent(void *thing)
{
cheat cheater;
cheater.vp = thing;
return( (cheater.gp)->getmntent() );
}
If possible, please email any replies.
thanks,
-- Bill Torcaso
sundial!wildbill@merk.com