开发者

Crash on calling ResetDC with devmode copied to byte array from marshalled structure

开发者 https://www.devze.com 2023-02-13 07:39 出处:网络
I am getting a System.AccessViolationException on a call to ResetDC when passing my Devmode. I am doing the following..

I am getting a System.AccessViolationException on a call to ResetDC when passing my Devmode. I am doing the following..

// create and marshall the devmode to a byte array.

DEVMODE myDevmode = new DEVMODE {dmSize = (short) Marshal.SizeOf(typeof (DEVMODE))};

myDevmode.dmFields = DM.Orientation;
myDevmode.dmOrientation = DMORIENT_LANDSCAPE;

IntPtr ptDM = Marshal.AllocHGlobal(myDevmode开发者_运维百科.dmSize);
Marshal.StructureToPtr(myDevmode, ptDM, false);

byte[] byteDM = new byte[myDevmode.dmSize];
Marshal.Copy(ptDM, byteDM, 0, myDevmode.dmSize);

I then call across a com interface (existing architecture not possible to change) the method:

SetDevMode(ref byteDM[0], myDevmode.dmSize)

on the other side of the com interface and back in .net code the other side the following is run:

    public void SetDevMode(ref byte pDevMode, int nDevModeSize)
    {
        _pageSetupDevMode = new byte[nDevModeSize];

        unsafe
        {
            fixed (byte* p = &pDevMode)
            {
                Marshal.Copy((IntPtr)p, _pageSetupDevMode, 0, nDevModeSize);
            }
        }
    }

and at a later point a call to ResetDC is made:

Win32.ResetDC(_hRefDc, ref _pageSetupDevMode[0]);

at which point I get the exception.

An unhandled exception of type 'System.AccessViolationException' occurred Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

This occurrs in gdi32.dll

Any ideas?


As mentioned in the comment above, this was not an issue with the memory handling but rather the result of passing an all but empty devmode into ResetDC - I had seen this done in a sample online but it seems to 'upset' gdi while printing.

I am now getting a valid devmode from the printer as the basis of the above code and this works fine. Apologies.

0

精彩评论

暂无评论...
验证码 换一张
取 消