Bill Walton
Bill Walton

Reputation: 823

How to wrap a C++ class with C++/CLI

So I'm trying to get my head around interoperability between C++ and C# using C++/CLI, creating a C++/CLI wrapper for an unmanaged C++ class, this is necessary because I need several instances of my C++ class in a C# app.

I made a CLR class library which uses pimpl to hide the unmanaged class like this

http://msdn.microsoft.com/en-us/library/ms235281.aspx

I had thought that building this project would result in a .lib file, but all that is output in the release folder is a DLL. I'm a little confused as I was lead to believe that you cannot export a class in C++/CLI, and that I would just link to the .lib file output by my CLR class library project. I can only assume I've created the wrong kind of project, but there doesn't seem to be much documentation on this kind of thing.

Thanks.

Upvotes: 3

Views: 4488

Answers (2)

Alastair Taylor
Alastair Taylor

Reputation: 425

What I have done in the past is very similar to the MSDN article

Create a C++ class and make sure the compiler options for that cpp file are set to "No Common Language RunTime Support"

Then use pimpl to reference this C++ class in a C++/CLI class making sure this cpp file has "Common Language RunTime Support (/clr)" enabled.

The output will be a DLL that you can use in existing .NET code.

From experience I would make sure the interface you create in the wrapper class has only doubles, int etc and not reference any C++ classes.

@Bill to use this wrapper DLL in some C# code simply add a reference to the DLL using "Add Reference". You will be able to call all public functions as you would expect.

Upvotes: 4

Nick
Nick

Reputation: 25799

What is output is a .Net Assembly which includes some native code. If you want to put your native code into a static library and then link that into this Assembly then that would work too.

But at the end of the day if you want to include your code in a .Net(c#) application then the .Net interface to it has to reside in an Assembly (.dll).

Upvotes: 3

Related Questions