I have a C++/CLI (VS 2008) mixed mode library that creates native objects and calls methods in then. Native dll is written in pure c++. Now in my C++/CLI wrapper methods if I declare object of native classes in c++ way as
ClassA obj;
Obj.Method();
and use it, it works but, I get System.AccessViolationException: Attempt to read or write protected memory when the program exists.
But if I do it this way
ClassA *obj = new ClassA();
Obj->Method();
it works fine.
So my question is why cant I declare a object just on stack the C++ way ?
Destructor in the native code is declared virtual. Is that the reason ?
No, this has nothing to do with stack vs heap. The stack in a managed program is no different from one in a native program. Using native code in a managed program doesn’t make it any less likely to cause it to destroy the heap, stomp the stack frame, overwrite the end of a buffer, invoke undefined behavior, the usual stuff that make native code crash with an access violation.
The difference between storing it on the stack vs the heap is the kind of damage that’s done. Yes, heap corruption can take a while to have side-effects. Usually much longer than stack frame corruption, including never.