c# - 如何释放/释放 IntPtr 到函数指针?

标签 c# native release free intptr

我有带有两个外部方法的 native 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的正确处理呢?

最佳答案

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

void Free(IntPtr handle);

你无法知道内存是如何分配的。如果内存是通过 C malloc 分配的,您甚至无法轻松释放它。更糟糕的是,如果它是 C++ 对象,则只有 C++ 才能正确地释放它(调用正确的析构函数)。它必须是为您提供释放其内存的方法的库。

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

关于c# - 如何释放/释放 IntPtr 到函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29077562/

相关文章:

file - 如何禁用Maven Release插件检查本地修改?

c# - Linq To SQL - 如何禁用关联加载?

c# - 连接池错误 LINQ to SQL

c# - 从 .Net 连接到 AS400

c# - 如何在 UpdatePanel 中添加我自己的自定义用户控件?

java - 使用 eclipse 在 java 中使用 native 库

c++ - C++0x什么时候发布,什么时候成为事实上的标准?

ios - native iOS 应用程序 : How do I retrieve the Twitter user ID with iOS 5?

java - 我在哪里可以找到 Java 库中 `native` 方法的源代码?

android - Gradle 发布构建失败