您的位置:首页 > 编程语言 > C语言/C++

C#调用返回C++指针的缓冲区,并释放

2012-12-30 13:54 666 查看
在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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: