微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/csharp/93213.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐