[LCP]CAllin c++ library function from C

Jack Lloyd lloyd at acm.jhu.edu
Thu Nov 21 04:02:01 UTC 2002


Yes. Generally it takes some work, but it's possible. Lets say the C++
function was:

double foo(int, std::string);

And you wanted to call it from C.

Write this function, compiling it as C++:

extern "C" double foo_wrap(int num, const char* str)
  {
  return foo(num, str);
  }

Then you call foo_wrap() in your code when you want to call foo()

The two fundamental issues are:

   Linking conventions. The 'extern "C"' magic takes care of that

   Type conversions. This may be done by the compiler, or it may require
   some work inside the wrapper function. In the example above,
   foo_wraps's const char* argument will be automatically converted into
   a std::string for calling foo()

Stroustrup's 'The C++ Programming Language' has a few examples of calling
C++ from C, and wrapping C functions for easier use in C++ [though of
course C++ can call bare C functions easily]

Things like objects, member functions, etc are a lot harder, though you can
do it with some trickery.

On Wed, 20 Nov 2002, David wrote:

> Is it possible to call a function that was written in c++ and is in a
> library from c program?
>
>
>




More information about the linuxCprogramming mailing list