Contents Up << >>

How can I pass an object of a C++ class to/from a C function?

Here's an example:

  	/****** C/C++ header file: Fred.h ******/
	#ifdef __cplusplus    /*"__cplusplus" is #defined if/only-if compiler
is C++*/
	  extern "C" {
	#endif

	#ifdef __STDC__
	  extern void c_fn(struct Fred*);	/* ANSI-C prototypes */
	  extern struct Fred* cplusplus_callback_fn(struct Fred*);
	#else
	  extern void c_fn();			/* K&R style */
	  extern struct Fred* cplusplus_callback_fn();
	#endif

	#ifdef __cplusplus
	  }
 	#endif

	#ifdef __cplusplus
	  class Fred {
	  public:
	    Fred();
	    void wilma(int);
	  private:
	    int a_;
	  };
	#endif
"Fred.C" would be a C++ module:

  	#include "Fred.h"
	Fred::Fred() : a_(0) { }
 	void Fred::wilma(int a) : a_(a) { }

	Fred* cplusplus_callback_fn(Fred* fred)
	{
	  fred->wilma(123);
	  return fred;
	}
"main.C" would be a C++ module:

  	#include "Fred.h"

	int main()
	{
	  Fred fred;
	  c_fn(&fred);
	  return 0;
	}
"c-fn.c" would be a C module:

  	#include "Fred.h"
	void c_fn(struct Fred* fred)
	{
	  cplusplus_callback_fn(fred);
	}
Passing ptrs to C++ objects to/from C fns will fail if you pass and get back something that isn't exactly the same pointer. For example, don't pass a base class ptr and receive back a derived class ptr, since your C compiler won't understand the pointer conversions necessary to handle multiple and/or virtual inheritance.