I am working on a .NET wrapper for the ANSI CCh library that looks like this:
EXTERNC void foo_init(void); EXTERNC char* foo_string_magic(const char *str); EXTERNC void foo_cleanup(void);
My C ++ / CLI wrapper looks like this:
public ref class FooWrapper abstract sealed { private: /// <summary> /// Provides an RAII context for native types lacking a destructor. /// </summary> static marshal_context ^_Context; /// <summary> /// Marshals .NET String to native const char*. /// </summary> static const char* _MarshalString(String ^str) { return _Context->marshal_as<const char*>(str); } public: /// <summary> /// Initializes foo. /// </summary> static void Initialize() { _Context = gcnew marshal_context(); foo_init(); } /// <summary> /// This function should be called once you're done with using foo. /// </summary> static void Cleanup() { foo_cleanup(); // uncommenting this line throws heap corruption error // delete _Context; } /// <summary> /// Foo magic! /// </summary> static String^ StringMagic(String ^str) { char *fooString = _MarshalString(str); return gcnew String(foo_string_magic(fooString)); } }
I am confused about the correct use of gcnew with marshal_context. MSDN uses gcnew to instantiate a marshal_context, while many online examples do not instantiate a marshal_context at all.
My questions:
- Using gcnew optional with marshal_context? If so, why?
- My wrapper is consumed by a C # application that causes cumulative corruption errors when calling Cleanup (). Why?
source share