gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:49 24 4
gpt4 key购买 nike

我有带有两个外部方法的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com