What is the basic structure of a wrapper to c++/cli so it can be called from c# ?
Asked
Active
Viewed 1,483 times
1
-
Do you want to wrap an *unmanaged* class in a C++/CLI wrapper to let C# use it? Or do you simply want to use a C++/CLI class from C#? – Matteo Italia Feb 13 '11 at 18:20
1 Answers
2
A wrapper for a C++ class Blah:
EDIT:
ref class BlahWrapper {
BlahWrapper () {
blah = new Blah();
}
!BlahWrapper() { //Destructor called by GC
if (blah != null) {
delete blah;
blah = null;
}
}
~BlahWrapper() { //Dispose() called in "using" blocks, or manually dispose
if (blah != null) {
delete blah;
blah = null;
}
}
private:
Blah* blah;
}

Yochai Timmer
- 48,127
- 24
- 147
- 185
-
Setting `blah = NULL;` after deleting would be nice. Also GC needs `!BlahWrapper()` destructor. – ali_bahoo Feb 13 '11 at 19:02
-
!BlahWrapper compiles into Dispose().... GC uses a normal destructor to destroy the object... And again, it's being deleted, the variable blah won't exist after that line. – Yochai Timmer Feb 13 '11 at 19:15
-
What do you mean by "a normal destructor." "!BlahWrapper" compiles into `Finalize()` which is invoked by GC. http://www.drdobbs.com/cpp/199601976;jsessionid=GEMCVL2U30511QE1GHPCKHWATMY32JVN?pgno=4 http://msdn.microsoft.com/en-us/library/ms177197(v=VS.90).aspx Unmanaged memory should be released in `!BlahWrapper()` which is the finalizer. If you release blah in destructor then setting it to NULL means telling GC that you have nothing to do with `blah` anymore. – ali_bahoo Feb 13 '11 at 21:10
-
Of course your code is not wrong. It will work without trouble if and only if OP deletes the instances of BlahWrapper himself. If not GC never frees the native or unmanaged resources, in this particular case `blah` pointer. – ali_bahoo Feb 13 '11 at 21:10