Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!sdd.hp.com!hplabs!hpcc05!hpsciz!masa From: masa@hpsciz.sc.hp.com (Masayoshi Habu) Newsgroups: comp.lang.c++ Subject: Re: calling C++ from C Message-ID: <1410004@hpsciz.sc.hp.com> Date: 17 Apr 91 16:21:58 GMT References: <1991Apr15.154120.13484@murdoch.acc.Virginia.EDU> Organization: Hewlett-Packard, Santa Clara, CA Lines: 45 In comp.lang.c++, masa@hpsciz.sc.hp.com (Masayoshi Habu) writes: In comp.lang.c++, 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. Do I have to determine how my compiler (Turbo C++ version 1.01) mangles names, and then call the member functions with those names? Sorry, I hit a wrong key while writing a response. Anyway, there is a "correct" way to call a member function from C. You don't have to figure out the function name. Let's have three global (non-member) functions for this object. The first function creates an object and returns its pointer to C. The second function receives the pointer and calls the member function with the pointer. The third function also receives the pointer and deletes it. All these function names need to be in the famous 'extern "C" {}' construct. Note that this construct works also for functions compiled by C++. It tells C++ compiler not to change the functions names appear in the '{}'. Suppose I have a class A, then extern "C" { A* create_object(); void call_member(A*); void delete_object(A*); } A* create_object() { return(new A()); } void call_member1(A* target) { target->member_function1(); } void delete_object(A* target) { delete target; } If you want to call a member function directly, then you need to get a pointer with the first function, then call the member function with the pointer as its first argument. Of course, you can 'cheat' to know the changed name of the member function by either looking at its C code (when your C++ compiler emits C) or searching a plausible name in your object file. But this is a non-standard way. masa