home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / cplus / 18220 < prev    next >
Encoding:
Text File  |  1992-12-21  |  1.7 KB  |  68 lines

  1. Path: sparky!uunet!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!magnus.acs.ohio-state.edu!usenet.ins.cwru.edu!agate!apple!kaleida.com!moon!gordie
  2. From: gordie@kaleida.com (Gordie Freedman)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to call C++ functions in a C progr
  5. Date: 18 Dec 1992 23:25:57 GMT
  6. Organization: Happy hacker bait and tackle shop
  7. Lines: 54
  8. Distribution: world
  9. Message-ID: <1gtmm5INN5o@golden.kaleida.com>
  10. References: <1gqe3lINNs1v@eagle.natinst.com>
  11. Reply-To: gordie@kaleida.com
  12. NNTP-Posting-Host: moon.kaleida.com
  13.  
  14. The best way to do this is have a wrapper function in the C++ code that
  15. the C function can call. Of course, this is not optimum performance, so
  16. hopefully things are encapsulated such that the calls from C to C++ are 
  17. infrequent, and frequent calls are within the same language.
  18.  
  19. By declaring foo1 and foo2 extern "C", the names do not get mangled. Note that if
  20. they are called from other C++ code in another file, that file must declare the
  21. references to foo1 and foo2 as extern "C" also.
  22.  
  23. Make sure you link with the c++ linker, it is also recommended that you compile
  24. main with a c++ compiler, to make sure that global constructors get called/etc.
  25.  
  26. -----------foo.C-----------------
  27. // This is C++ code
  28. extern "C" int foo1 (int, int);
  29. extern "C" int foo2 (int, int);
  30.  
  31. int bar (int x, int y)
  32. {
  33.     int someInt;
  34.     // do some fancy C++ stuff
  35.     return someInt;
  36. }
  37.  
  38. int foo1 (int x, int y)
  39. {    
  40.     return bar (x, y);
  41. }
  42.  
  43. int foo2 (int x, int y)
  44. {
  45.     int z;
  46.     // Do some fancy C++ stuff
  47.     return z;
  48. }
  49. ---------test.c-----------------
  50.  
  51. /* This is C code */
  52. extern int foo1 (int, int);
  53. extern int foo2 (int, int);
  54.  
  55. void
  56. test (void)
  57. {
  58.     /* stuff ... */
  59.     a = foo1 (1, 2);
  60.     /* More stuff */
  61.     a = foo2 (10, 20);
  62. }
  63.  
  64. ---
  65. Gordie Freedman: gordie@kaleida.com Sigs are for kids
  66.  
  67.  
  68.