Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a C++ library in a C# app?

Thus far I've figured out out I needed to recompile the library as a .dll instead of a .lib, enable /clr and /EHa instead of /EHsc. Now I've got a managed dll which I've added as a reference in my C# project.

Now how do I use it?

I'm prepared to write some wrappers, but I don't know where to begin or how to "see" what functions I've gained access to. I've read a little bit about how the class names and functions might be mangled by the compiler... do I need to go back and add __declspec exports everywhere (if so, how?), or is there an option in VS2010 that says "don't mangle it!"?

The C++ library in question is still under active development, so I'm hoping I can modify the C++ library as little as possible and just recompile it periodically with a few switches, and then expose the new functionality as I need it.

like image 377
mpen Avatar asked Oct 25 '10 00:10

mpen


People also ask

How does a library work in C?

C libraries store files in object code; during the linking phase of the compilation process ( Compilation Process) files in object code are accessed and used. It is faster to link a function from a C library than to link object files from a separate memory sticks or discs.

Do I need to download C libraries?

These libraries are required by many applications built by using Microsoft C and C++ tools. If your app uses those libraries, a Microsoft Visual C++ Redistributable package must be installed on the target system before you install your app.

What is ac library good for?

The C standard library provides macros, type definitions and functions for tasks such as string handling, mathematical computations, input/output processing, memory management, and several other operating system services.


2 Answers

If you are going to compile your C++ (if originally was unmanaged C++) you will need to do much more than just add the /clr switch. In order for C# to use the DLL you will need to create managed classes and other types based on CTS which are compatible with C# (.NET).

See and ref classes.

A good book to read about the subject (IMHO) is this one

like image 55
AndersK Avatar answered Sep 20 '22 06:09

AndersK


You can either expose the functions as C style functions (i.e., no mangling) from your dll or you can expose them as COM objects.

like image 29
Ed S. Avatar answered Sep 19 '22 06:09

Ed S.