C#释放IntPtr引用的内存

前端之家收集整理的这篇文章主要介绍了C#释放IntPtr引用的内存前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用一些非托管代码,它将指针(IntPtr)返回给大型图像对象.我使用引用,但在完成图像之后,我需要释放指针引用的内存.目前,唯一可以释放内存的是关闭整个应用程序.我需要能够从我的应用程序内释放内存.

这是调用分配内存的调用. hbitmap是返回的指针,需要解除分配.

[DllImport("twain_32.dll",EntryPoint = "#1")]
public static extern TwainResult DsImageTransfer(
    [In,Out] Identity origin,[In] Identity dest,DataGroup dg,DataArgumentType dat,Message msg,ref IntPtr hbitmap);

解决方法

这将取决于如何分配记忆. Marshal类具有通过共同的互配分配模式分配的内存的方法,如 FreeCoTaskMem.如果非托管代码使用非Interop兼容的分配方式,那么您不能互操作.

更新

如果我冒昧猜测,twain_32.dll中调用函数#1是TWAIN提供程序中的DS_ENTRY函数. Twain specifications调出内存资源管理协议:

Memory Management in TWAIN 2.0 and
Higher

TWAIN requires Applications and
Sources to manage each other’s memory.
The chief problem is guaranteeing
agreement on the API’s to use. TWAIN
2.0 introduces four new functions that are obtained from the Source Manager
through DAT_ENTRYPOINT.

TW_HANDLE PASCAL DSM_MemAllocate (TW_UINT32)
PASCAL DSM_MemFree (TW_HANDLE)
TW_MEMREF PASCAL DSM_MemLock(TW_HANDLE)
void PASCAL DSM_MemUnlock(TW_HANDLE)

These functions correspond to the
WIN32 Global Memory functions
mentioned in prevIoUs versions of the
TWAIN Specification: GlobalAlloc,
GlobalFree,GlobalLock,GlobalUnlock
On MacOS/X these functions call
NewPtrClear and DisposePtr. The lock
and unlock functions are no-ops,but
they still must be called. TWAIN 2.0
compliant Applications and Sources
must use these calls on all platforms
(Windows,MacOS/X and Linux). The
Source Manager takes the
responsibility to make sure that all
components are using the same memory
management API’s.

所以为了释放资源,你应该调用DSM_MemFree,据说Win32平台将通过GlobalFreeMarshal.FreeHGlobal实现.

由于这主要是我的猜测,您最好使用您使用的特定TWAIN实现的规范进行验证.

原文链接:https://www.f2er.com/csharp/93213.html

猜你在找的C#相关文章