I am using some unmanaged code that is returning pointers (IntPtr) to large image objects. I use the references but after I am finished with the images, I need to free that
That would depend on how that memory was allocated. The Marshal class has methods for deallocating memory allocated through the common interop allocation patterns, like FreeCoTaskMem. If the unmanaged code uses a non Interop compatible way of allocating, then you cannot interop with it.
Updated
If I would venture a guess, the function #1 you invoke in twain_32.dll is the DS_ENTRY function in a TWAIN provider. The Twain specifications call out the memory resource management protocol:
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 callNewPtrClear
andDisposePtr
. 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.
So to free resources you're supposed to call DSM_MemFree, which supposedly on Win32 platforms would be implemented through GlobalFree, or Marshal.FreeHGlobal.
Since this is mostly speculation on my part, you better validate with the specs of the specific TWAIN implementation you use.