如何释放/释放IntPtr函数指针?

时间:2015-03-16 13:05:14

标签: c# native release free intptr

我有两个外部方法的原生DLL(没有来源):InitDoSomeWork

这是我的类包装器:

public class MyClass : IDisposable
{
[DllImport(@"myDLL.dll",
SetLastError = true,
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi,
EntryPoint = "EntryPoint#1",
ExactSpelling = true)]
private static extern IntPtr InitNative();

[DllImport(@"myDLL.dll",
SetLastError = true,
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi,
EntryPoint = "EntryPoint#2",
ExactSpelling = true)]
private static extern ushort DoSomeWorkN(byte[] arrayOut, [In] IntPtr initHandle);

private readonly IntPtr _initHandle;

public MyClass()
{
    _initHandle = InitNative();
}

protected override byte[] DoSomeWork()
{ 
  ...
    DoSomeWorkN(buffOut, _initHandle);
  ...
}

public override void Dispose()
{
    //???
}

我试过了:

Marshal.FreeHGlobal(_initHandle); //throws exception: Invalid access to memory location. (Exception from HRESULT: 0x800703E6)"}
Marshal.FreeCoTaskMem(_initHandle); //throws Access violation exception
Marshal.FreeBSTR(_initHandle); //doesn't throw exception, but doesn't work (after calling that method IntPtr isn't IntPtr.Zero)

那么,如何正确处理_initHandle?

1 个答案:

答案 0 :(得分:3)

您的图书馆应该 / 必须 为您提供第三种方法:

void Free(IntPtr handle);

您无法知道内存的分配方式。如果内存是通过C malloc分配的,那么您甚至无法轻松释放它。更糟糕的是,如果它是一个C ++对象,只有C ++可以正确地释放它(调用正确的析构函数)。它必须是库,为您提供一种释放其记忆的方法。

(从技术上讲,你甚至不知道IntPtr是什么:-)也许它不是真正的指针。它可能是一个数字,你不必释放任何东西......或者它可能是Win32 HANDLE返回的CreateFile