Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!rpi!crdgw1!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: calling C++ from C Message-ID: <673@taumet.com> Date: 16 Apr 91 15:39:27 GMT References: <1991Apr15.154120.13484@murdoch.acc.Virginia.EDU> Organization: Taumetric Corporation, San Diego Lines: 51 pts@faraday.clas.Virginia.EDU (Paul T. Shannon) writes: >Though many books explain how to call C functions from C++, I'm >having difficulty figuring out how to do the opposite. >I have a large C program, built from several modules of Ansi C >code. I want to add two C++ modules to this, and call the member >functions from the C program. It is interesting that this question comes up three times in today's news. The answer is that the same mechanism serves both requirements. You may declare and define a C++ function as extern "C" ... and call it from a C program, as long as 1. The function is not a member of any class. 2. No more than one overloaded version of the function is so declared. 3. The function declaration requires only types visible to the C program. Requirement 3 can be relaxed a bit by using pointers to C++ class types, if no object of the type is needed by the C program. That is, a C++ function can pass a pointer to a class object to a C function, which can pass on that pointer to another C++ function. In the C file, you just use the incomplete declaration struct SomeClass; and then use pointers to struct SomeClass. You cannot safely provide "equivalent" C declarations of C++ classes, since you cannot portably predict how the C++ compiler will lay out the class members. You can relax Requirements 1 and 2 by providing "wrapper functions" in C++. Example: C++ file: ========= class SomeClass { ... int f1(int); ... }; extern "C" int call_f1(SomeClass* p, int i) // wrapper for C { return p->f1(i); } C file: ======== struct SomeClass; /* defined in C++ files */ int call_f1(struct SomeClass*, int); /* defined in C++ files */ int myfunc(struct SomeClass* p) { ... call_f1(p, 3) ... } -- Steve Clamage, TauMetric Corp, steve@taumet.com