Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

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

class function object pass
0
Posted

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

0

Here’s an example (for info on extern C, see the previous two FAQs). Fred.h: /* This header can be read by both C and C++ compilers */ #ifndef FRED_H #define FRED_H #ifdef __cplusplus class Fred { public: Fred(); void wilma(int); private: int a_; }; #else typedef struct Fred Fred; #endif #ifdef __cplusplus extern “C” { #endif #if defined(__STDC__) || defined(__cplusplus) extern void c_function(Fred*); /* ANSI-C prototypes */ extern Fred* cplusplus_callback_function(Fred*); #else extern void c_function(); /* K&R style */ extern Fred* cplusplus_callback_function(); #endif #ifdef __cplusplus } #endif #endif /*FRED_H*/ Fred.cpp: // This is C++ code #include “Fred.h” Fred::Fred() : a_(0) { } void Fred::wilma(int a) { } Fred* cplusplus_callback_function(Fred* fred) { fred->wilma(123); return fred; } main.cpp: // This is C++ code #include “Fred.h” int main() { Fred fred; c_function(&fred); return 0; } c-function.c: /* This is C code */ #include “Fred.h” void c_function(Fred* fred) { cplusplus

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123