I have been getting 'access violation reading location' errors
occasionally in my app. I have debugged this and found it is one of my
interop functions. Am I doing anything wrong here? The unmanaged
function takes a pointer to some bytes in memory and a long, and
returns a pointer which points somewhere into those bytes based on the
long value.
My interop code is like so:
[DllImport("ImageFile.dll", EntryPoint =
"?PB_SkipBytes@@YAPAEPAEJ@Z", CallingConvention =
CallingConvention.Cdecl)]
public static extern IntPtr PB_SkipBytes(IntPtr pIn, int
bytesToSkip);
public static Byte[] SkipBytes(Byte[] bytToDecompress, int
intBytesToSkip)
{
IntPtr pbData;
IntPtr pbByteArray;
System.Diagnostics.Debug.WriteLine("Entering Skipbytes
function");
// Pin the array in memory so the garbage collector can't move
it around
System.Diagnostics.Debug.WriteLine("About to pin array");
GCHandle pinnedArray = GCHandle.Alloc(bytToDecompress,
GCHandleType.Pinned);
System.Diagnostics.Debug.WriteLine("Pinned array -
byttodecompress length is " + bytToDecompress.Length);
// Get a pointer to the beginning of the pinned byte array
pbByteArray = pinnedArray.AddrOfPinnedObject();
System.Diagnostics.Debug.WriteLine("Got pointer");
// Call the skip bytes function and get a pointer to the
remaining uncompressed data
System.Diagnostics.Debug.WriteLine("Skipping " + intBytesToSkip
+ " bytes");
pbData = PB_SkipBytes(pbByteArray, intBytesToSkip);
System.Diagnostics.Debug.WriteLine("Called");
// Calculate the size of the new managed array and allocate
int intNewCompressedArraySize = (pbByteArray.ToInt32() +
bytToDecompress.Length) - pbData.ToInt32();
System.Diagnostics.Debug.WriteLine("Calculating new array
size");
byte[] bytBuffer = new byte[intNewCompressedArraySize];
// Copy the remaining uncompressed data into the buffer
System.Diagnostics.Debug.WriteLine("Copying to new array");
Marshal.Copy(pbData, bytBuffer, 0, intNewCompressedArraySize);
System.Diagnostics.Debug.WriteLine("Copied to new array");
// return buffer and free memory
pinnedArray.Free();
return bytBuffer;
}
Mattias Sjögren - 28 Sep 2006 20:33 GMT
>I have been getting 'access violation reading location' errors
>occasionally in my app. I have debugged this and found it is one of my
>interop functions. Am I doing anything wrong here?
The code looks good to me. Are you sure the error isn't in the native
code?
Mattias

Signature
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.