News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

Interfacing to C - C Functions Calling C++

Started by ben2ong2, October 06, 2006, 10:55:15 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

PROBLEM: What is the safest way for C functions to call C++ functions?

RESPONSE: Steve Clamage (steve@taumet.com), TauMetric Corp, 25 Jan 92


There is no guarantee that any C++ function uses the same calling
mechanism as any C function (or function in any other language).
A static function does not have a 'this' parameter, but any C++
function might have some sort of "hidden" parameter for any purpose.

Functions with no parameters and no return value eliminate several
kinds of complication with calling sequences, but there still remain
other problems.  For example, in typical implementations the calling
function and the called function have to agree on
  -  who removes the return address and frame pointer from the stack;
  -  which registers must be saved and restored;
  -  who does the register saving and restoring.

There is no rule that the C++ and C compilers have to do these things
the same way  (when you use an object-code C++ compiler).

The ONLY safe way to call a C++ function from C is to declare it 'extern
"C"'.  No member function may be so declared, so the only safe way to
call one is to write a wrapper function.

Example:

        class C { ... static void foo(); ... };
        extern "C" C_foo() { C::foo(); }

If the static member function exists so it can be called externally,
make it a friend function instead of a static member.  Then it may
be declared 'extern "C"' directly.

You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login