mpen
mpen

Reputation: 282875

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.

Upvotes: 12

Views: 558

Answers (4)

H. den Breejen
H. den Breejen

Reputation: 113

Yes, wrap it in à COM object. I believe ATL is what you meed to do this with the least effort.

Upvotes: 2

Nick
Nick

Reputation: 6846

I'd suggest writing a COM wrapper, and using that instead. Have a look at http://msdn.microsoft.com/en-us/library/035x3kbh%28v=VS.80%29.aspx for intro instructions. You'll want to make your object interfaces derived from IDispatch and be automation compatible, which should enable the runtime to consume them without any custom marshaling.

A nice benefit of this approach is you can continue to build your native code as a library, and just make your COM project use it. Also, it's still native code inside the COM object, so there's much less potential for unknown problems (once you get the interface layer working).

That's my suggestion, anyway.

Upvotes: 4

Ed Swangren
Ed Swangren

Reputation: 124642

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.

Upvotes: 6

AndersK
AndersK

Reputation: 36082

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

Upvotes: 8

Related Questions