我正在为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。
我的问题是: