在C++的函数中new了一段内存
char *test(char* filename)
{
new一段内存
}
void release(char *mm);
{
delete一段内存
}
[DllImport("test.dll", EntryPoint = "test", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr test( string filename);
[DllImport("test.dll", EntryPoint = "release", CallingConvention = CallingConvention.Cdecl)]
public static extern void release(IntPtr sb);
public static IntPtr GetPtr(string filename)
{
return test(filename);
}
static unsafe void Main(string[] args)
{
string sb = @"路径名";
IntPtr re = XX.GetPtr(sb);
string result = Marshal.PtrToStringAnsi(re);
//释放非托管代码申请的内存
XX.release(re);
//内存已释放,所以打印结果为空
Console.WriteLine(Marshal.PtrToStringAnsi(re));
//result引用的对象是已释放的对象的副本,所以打印结果为所需结果
Console.WriteLine(result);
Console.ReadLine();
}