Reputation: 113946
You can create a VC++ Windows Forms project that runs on the CLR, which is essentially a .NET app written in C++. Can you use unmanaged C++ libraries directly from such a project? Does that mean that the library must compile and run under .NET? Or must you write CLR wrapper classes for such libraries and only those will be usable from the CLR app?
Upvotes: 0
Views: 1110
Reputation: 283614
Using a smart pointer library makes it much simpler to manage allocation of native (not garbage collected) objects, which is surprisingly difficult in the presence of exceptions, multiple calls to Dispose()
, forgetting to call Dispose()
, etc.
Here's Dr_Asik's example, rewritten to use a smart pointer I wrote:
#include "clr_scoped_ptr.h"
#include "NativeClass.h"
public ref class NativeClassWrapper {
clr_scoped_ptr<NativeClass> m_nativeClass;
public:
NativeClassWrapper() m_nativeClass(new NativeClass()) {}
// auto-generated destructor is correct
// auto-generated finalizer is correct
void Method() {
m_nativeClass->Method();
}
};
For string conversions, use the marshal_as
class Microsoft provided for the purpose. Check out ildjarn's answer here: C++/CLI String Conversions
Upvotes: 1
Reputation: 3499
Yes. Here are some guides. Mixing CLI/C++ and native code. You don't need a wrapper to use them in CLI/C++. In fact, you use CLI/C++ and native code to create a wrapper.
http://www.technical-recipes.com/2012/mixing-managed-and-native-types-in-c-cli/
http://www.codeproject.com/Articles/35041/Mixing-NET-and-native-code
If you are actually trying to make a wrapper to use in C#, it should look something like this:
#include "NativeClass.h"
public ref class NativeClassWrapper {
NativeClass* m_nativeClass;
public:
NativeClassWrapper() { m_nativeClass = new NativeClass(); }
~NativeClassWrapper() { delete m_nativeClass; }
void Method() {
m_nativeClass->Method();
}
protected:
// an explicit Finalize() method—as a failsafe
!NativeClassWrapper() { delete m_nativeClass; }
};
Refer to C++/CLI wrapper for native C++ to use as reference in C#
Upvotes: 1