IntPtr to Byte Array and Back

后端 未结 2 821
野的像风
野的像风 2020-12-10 07:29

Referencing How to get IntPtr from byte[] in C#

I am attempting to read the data that an IntPtr is referencing into a byte [] and then back into another IntPtr. The

相关标签:
2条回答
  • 2020-12-10 07:44

    1- I assume bmpptr is already an unmanaged pointer, if so why do you need to 'round-trip' this back to an unmanaged pointer unmanagedPointer?

    2- Marshal.SizeOf will not give you the size of the unmanaged memory allocation.

    Using Marshal.Copy, you can copy the contents of unmanaged memory to a managed byte array, but you will need to know how many bytes need to be moved from the unmanaged buffer to the managed buffer. The API should ideally provide this information.

    0 讨论(0)
  • 2020-12-10 08:01

    The exception thrown by the call to SizeOf is correct; the method has no way of knowing what the length of the array that you are passing to it is, it just has a pointer.

    To that end, the easiest way to get the data is to call the static Copy method on the Marshal class, passing the pointer to the unmanaged data, the index and number of bytes to read, as well as a pre-allocated buffer of bytes to marshal the data into.

    As for getting the size of the array, as Anton Tykhyy pointed out in the comments, it appears (be very careful here) that the call to Twain.GlobalLock(hImage) is using memory allocated by GlobalAlloc, which means that you can make a call to the GlobalSize API function through the P/Invoke layer to get the size.

    If it is not a handle to something allocated by a call to GlobalAlloc then you need to find out how the Twain module is allocating the memory and use the appropriate mechanism to determine the length of the memory pointed to by the IntPtr.

    0 讨论(0)
提交回复
热议问题