gcnew是否可选marshal_context?

时间:2012-11-10 19:16:57

标签: .net memory-management c++-cli marshalling

我正在为ANSI C库开发.NET包装器。 C .h看起来像这样:

EXTERNC void foo_init(void);

EXTERNC char* foo_string_magic(const char *str);

EXTERNC void foo_cleanup(void);

我的C ++ / CLI包装器如下所示:

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's magic!
        /// </summary>
        static String^ StringMagic(String ^str)
        {
            char *fooString = _MarshalString(str);

            return gcnew String(foo_string_magic(fooString));
        }
}

我对使用marshal_context正确使用gcnew感到困惑。 MSDN使用gcnew来实例化marshal_context,而许多在线示例根本没有实例化marshal_context。

我的问题是:

  1. 使用gcnew可选和marshal_context?如果是这样,为什么?
  2. 我的包装器由C#应用程序使用,该应用程序在调用Cleanup()时会引发堆损坏错误。为什么?

0 个答案:

没有答案