[Mono-list] How to create C++ library and call it's functions from C# program?

Marcus mathpup@mylinuxisp.com
Thu, 11 Mar 2004 19:00:52 +0000


On Friday 12 March 2004 12:14 am, Jonathan Pryor wrote:

> 2.  C++ compilers use a technique called "name mangling", so that you
> can have function overloads.  For example, your "print (const char*)"
> function is *actually* the linker symbol:

> The right way is to instead tell the C++ compiler to disable name
> mangling.  This is done by using an ``extern "C"'' modifier in your C++
> code.  The downside to this is that you can not have two C++ function
> overloads that are both marked as ``extern "C"'', as this would cause
> confusion.

I would also add that the ``extern "C"'' does not help in situations where you 
need to communicate with C++ classes. In this case, with GCC an intermediate 
C library is almost certainly necessary. If something similar VS.NET's 
Managed Extensions for C++ existed for GCC, this might be avoided.

There at least 3 reasons why an intermediate layer is needed. First, there is 
no way to create a new instance of a C++ object from outside C++ unless the 
C++ library provides an appropriate function. There is no obvious way to 
determine how much memory to allocate for a given C++ object, so even if it 
were possible to call a C++ constructor directly to initialize the object, 
allocating the object in the first place seems impossible. 

Second, C++ compilers use name-mangling to avoid duplication of symbols when 
several classes define the same method and when overloaded methods are used. 
This mangling is platform dependent. It is possible to use system-specific 
utilities to produce a list of mangled and unmanagled names and then match 
them up to create a conversion table. So this is more of an annoyance than an 
an outright dead-end. 

Third, when optimization is specified, C++ compilers frequently inline any 
methods those bodies are defined within the class scope (and possibly other 
methods as well). Moreover, if every invocation of a method is inlined, some 
compilers do not by default emit an out-of-line copy for the method.