c# - Marshal.PtrToStructure access violation -


can see why it's failing ? if replace "out intptr lpvobject" "ref bitmap lpvobject", work way. can't see wrong code is.

using system; using system.runtime.interopservices; using system.drawing;  namespace program {   class core   {     [structlayout(layoutkind.sequential)]         public struct bitmap     {         public int32  bmtype;         public int32  bmwidth;         public int32  bmheight;         public int32  bmwidthbytes;         public uint16 bmplanes;         public uint16 bmbitspixel;         public intptr bmbits;     }       [dllimport("gdi32.dll", charset=charset.auto, setlasterror=true)]       public static extern int getobject ( intptr hgdiobj, int cbbuffer, out intptr lpvobject );       static void main(string[] args)     {       bitmap testbmp = new bitmap ( 10, 10 );       bitmap bitmapstruct = new bitmap();       intptr pbitmapstruct, pbitmapstructsave;       int    status;        pbitmapstructsave = pbitmapstruct = marshal.allochglobal ( marshal.sizeof(bitmapstruct) );        status = getobject ( testbmp.gethbitmap(), marshal.sizeof (bitmapstruct), out pbitmapstruct );        console.writeline ( "\nbytes returned " + status + ", buffer address = " + pbitmapstruct );        try       {         bitmapstruct = (bitmap) marshal.ptrtostructure ( pbitmapstruct, typeof(bitmap) );       }       catch ( exception ex )       {         console.writeline ( ex.message );       }        marshal.freehglobal(pbitmapstructsave);     }   } } 

the output is:

bytes returned 32, buffer address = 42949672960

unhandled exception: system.accessviolationexception: attempted read or write protected memory. indication other memory corrupt.

at system.runtime.interopservices.marshal.ptrtostructure(intptr ptr, type structuretype)

at program.core.main(string[] args) in d:\data\projects\test\test\program.cs:line 41

could because you're using wrong signature?

[dllimport("gdi32.dll")] static extern int getobject(intptr hgdiobj, int cbbuffer, intptr lpvobject);

http://www.pinvoke.net/default.aspx/gdi32/getobject.html

also, out means value needs initializes within method , not happening since have lpvobject defined.


Comments