accessing unmanaged memory [modified]
-
Hi, I am trying to access unmanaged memory which allocated from a dll function. The function signature that is exported is as follows
extern "C" __declspec( dllexport ) BOOL ResizeImage(LPVOID pbySrcBytes, LONG lnSrcSize, LPVOID pbyDestBytes, LPLONG lnTgtSize );
Through the parameter "pbySrcBytes" I pass memory to the unmanaged code using marshalling. In return the unmanaged function returns memory through "pbyDestBytes" on unmanaged heap which is having dynamic size which I get through "lnTgtImgSize". I am not able to copy the memory returned. I am getting an error as "Access Violation" & "the memory is corrupted". I have imported the function as follows.[DllImport("ImgProcessor.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)] public static extern Int32 ResizeImage([Out] byte[] pbySrcImgBytes, Int32 lnSrcImgSize, IntPtr ppbyDestImgBytes, [Out] IntPtr lnTgtImgSize );
I have done the C# part as follows:-byte []byInputArray = File.ReadAllBytes(txtInput.Text); // txtInput.Text contains the file name to read Int32 nTgtImgSize = new Int32(); IntPtr ptrTargetImageBytes = Marshal.AllocHGlobal(4); IntPtr ptrTgtImgSize = Marshal.AllocHGlobal(4); IntPtr ptrSourceImageBytes = Marshal.AllocHGlobal(byInputArray.Length); Marshal.StructureToPtr(byInputArray[byInputArray.Length-1], ptrSourceImageBytes, false); ImageResizerClient.ResizeImage(byInputArray, (int)byInputArray.Length, 400, 300, ptrTargetImageBytes, ptrTgtImgSize); nTgtImgSize = Marshal.ReadInt32(ptrTgtImgSize); byte []byOutputArray = new byte[nTgtImgSize]; Marshal.Copy(ptrTargetImageBytes, byOutputArray, 0, nTgtImgSize);
The Marshal.Copy method call is throwing the error. Can anyone help me understand why this is happening? Thank You, Amit. -- modified at 23:59 Monday 11th September, 2006