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实现的规范进行验证.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...