Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!uwm.edu!cs.utexas.edu!ut-emx!slcs.slb.com!asc.slb.com!hargrove From: hargrove@asc.slb.com (Jim Hargrove) Newsgroups: comp.lang.c++ Subject: Re: call C++ from C Message-ID: <1991Jun29.142749.26044@asc.slb.com> Date: 29 Jun 91 14:27:49 GMT References: <359@soleil.jupiter.UUCP> <20463@alice.att.com> <1991Jun28.153143.5476@ccu.umanitoba.ca> Sender: news@asc.slb.com Organization: Schlumberger Austin Systems Center Lines: 78 In-Reply-To: dab@ubitrex.mb.ca's message of 28 Jun 91 15:31:43 GMT Nntp-Posting-Host: bart >>>>> dab@ubitrex.mb.ca (Danny Boulet) writes: The listing below shows one way of calling a C++ function from a C program. There is one slight enhancement that we can make. Instead of propagating yet another void *, we can define a C typedef to use in pointing to a C++ object. In the case below, where the class is named fred, we define typdef struct fred * CFred_t; As the struct fred is not defined in the C scope this is an "incomplete" type definition in ANSI C. Only pointers can be defined in this way. Then the definition of the function freddoit becomes int freddoit(CFred_t myFred, int x); This means that the compiler can distinguish between pointers to freds and pointers to other objects. We should avoid void * whenever possible. dab> In article <20463@alice.att.com> ark@alice.UUCP () writes: >In article <359@soleil.jupiter.UUCP> rh@jupiter.UUCP (#Rachid Himmi) writes: > >> I'm looking for the way to call a C++ module from a C program through >> the declaration of a class and the call of its function members. dab> In your C++ code, write C callable functions that invoke the C++ members. dab> For example: dab> ---------------------- C++ code ------------------------ dab> class fred { dab> public: dab> . dab> . dab> . dab> int doit(int x); dab> . dab> . dab> . dab> }; dab> extern "C" int dab> freddoit(void *ptr,int x) dab> { dab> fred *p = (fred *)ptr; dab> return( p->doit(x) ); dab> } dab> ---------------------------------------------------------- dab> Call "freddoit" from C with a pointer to an instance of "fred" as the first dab> parameter and (in this example) an appropriate value for "x" as the dab> second parameter: dab> ---------------------- C code ---------------------------- dab> w = freddoit(fredptr,124); dab> ---------------------------------------------------------- dab> I've no idea if this is supposed to work but it does for me. > >Turn your C program into a C++ program and it's easy. >Otherwise, it's a matter between you and your implementer(s) >and it's not guaranteed to work no matter what you do. >-- > --Andrew Koenig > ark@europa.att.com -- -- jwh