• Advertisement
Sign in to follow this  

c and c++

This topic is 3953 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys, I have a program that uses a c and a c++ compiler and then links the results into one app. I know this isnt pretty but there is no way to prevent it in this app. Now my problem is that I want to pass a class from the c++ side to the c side. Since c doesnt have classes I am looking for a workaround. Is it maybe possible to have the c++ class inherit from a struct which declares the functions required and then pass a pointer to that struct? Any other ideas that are have way pretty? -CProgrammer

Share this post

Link to post
Share on other sites

On one end of the spectrum, you have a C interface which might look like this:

struct myclass;
typedef struct myclass myclassptr;

myclassptr CreateMyClass( ... );
void DestroyMyClass( myclassptr );
unsigned GetMyClassMember( myclassptr );

This is relatively easy -- you can define the structure on the C++ side of things only, and in C++, structures and classes are synonymous (with only effects on default access). The functions you can define inline to your C++ with `extern "C"`. The C API only interacts with myclass*, never myclass, so it doesn't even need to know the definition. This lets you use a non-POD myclass.

On the other hand, you may have a class which you need to store on the stack in your C code, involving virtual functions. In this case, you basically have to implement the class in C:

typedef struct myclass_vtable {
unsigned (*get_member)( myclassptr );
} *myclass_vtable_ptr;

struct myclass {
/* special */
myclass_vtable_ptr _vtable;

/* public */

/* private */
unsigned _a, _b;

unsigned GetMyClassMemberDefaultImpl( myclassptr self ) {
return self->_a + self->_b;

myclass_vtable default_vtable = {

void InitializeMyClass( myclassptr self ) {
self->_vtable = &default_vtable;
self->_a = 42;
self->_b = 24;

void CleanupMyClass( myclassptr self ) {
/* any cleanup code that might be necessary */

unsigned GetMyClassMember( myclassptr self ) {
return (*(self->_vtable->get_member))( self );

And no, you can't clean up the syntax for your C++ code without doing one of the following:
1) Invoking undefined behavior
2) Wrapping the entire thing

[Edited by - MaulingMonkey on May 23, 2007 10:28:39 AM]

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement