gpt4 book ai didi

c# - Marshal.PtrToStructure 访问冲突

转载 作者:行者123 更新时间:2023-11-30 23:22:37 27 4
gpt4 key购买 nike

谁能看出它失败的原因?如果我用“ref BITMAP lpvObject”替换“out IntPtr lpvObject”,我可以让它以这种方式工作。但我看不出代码有什么问题。

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 is " + Status + ", buffer address = " + pBitmapStruct );

try
{
BitmapStruct = (BITMAP) Marshal.PtrToStructure ( pBitmapStruct, typeof(BITMAP) );
}
catch ( Exception Ex )
{
Console.WriteLine ( Ex.Message );
}

Marshal.FreeHGlobal(pBitmapStructSave);
}
}
}

输出是:

Bytes returned is 32, buffer address = 42949672960

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is 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

最佳答案

会不会是因为你使用了错误的签名?

[DllImport("gdi32.dll")]static extern int GetObject(IntPtr hgdiobj, int cbBuffer, IntPtr lpvObject);

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

另外,out 意味着该值需要在方法中初始化,这可能不会发生,因为您已经定义了 lpvObject

关于c# - Marshal.PtrToStructure 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38703341/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com