C# 联合结构编码

标签 c# mono marshalling ioctl

我正在尝试将 Video4Linux 集成到我的托管应用程序中。事实上,我已经声明了所有必需的结构和相关的ioctl。在这个问题中,我提出了两个ioctl:SetFormatGetFormat;虽然前者运行良好(就像我实际使用的其他十几个一样),但后者却给我带来了糟糕的内存行为。

GetFormat ioctl 实际上正在执行,但是一旦应用程序访问 ioctl 参数(调试器或我的应用程序本身),它总是崩溃并出现以下堆栈:

System.NullReferenceException: ...
at System.String.mempy4(...) in <filename unknown>:0
at System.String.memcpy(...) in <filename unknown>:0
at Derm.Platform.Video4Linux.ControlGetFormat(...) in <...>
...

我对 p/invoking ioctl 做了一些调查,再一次,我不明白为什么我的应用程序崩溃了。我怀疑这是因为结构内存布局,但我无法解释为什么 SetFormat 工作而 GetFormat 不工作(因为它们使用完全相同的参数)。

我必须 P/Invoke 接收/返回结构 v4l2_formatioctl 例程:

struct v4l2_format {
        enum v4l2_buf_type type;
        union {
                struct v4l2_pix_format          pix;     /* V4L2_BUF_TYPE_VIDEO_CAPTURE */
                struct v4l2_pix_format_mplane   pix_mp;  /* V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE */
                struct v4l2_window              win;     /* V4L2_BUF_TYPE_VIDEO_OVERLAY */
                struct v4l2_vbi_format          vbi;     /* V4L2_BUF_TYPE_VBI_CAPTURE */
                struct v4l2_sliced_vbi_format   sliced;  /* V4L2_BUF_TYPE_SLICED_VBI_CAPTURE */
                __u8    raw_data[200];                   /* user-defined */
        } fmt;
};

struct v4l2_pix_format {
    __u32                   width;
    __u32                   height;
    __u32                   pixelformat;
    enum v4l2_field         field;
    __u32                   bytesperline;   /* for padding, zero if unused */
    __u32                   sizeimage;
    enum v4l2_colorspace    colorspace;
    __u32                   priv;           /* private data, depends on pixelformat */
};

我使用下面的形式翻译了结构v4l2_format

[StructLayout(LayoutKind.Explicit, Pack = 4, CharSet = CharSet.Ansi)]
public struct Format
{
    public Format(BufferType bufferType)
    {
        Type = bufferType;
        Pixmap = new PixmapFormat();
        RawData = new byte[RawDataLength];
    }

    public Format(BufferType bufferType, PixmapFormat pixmapFormat)
    {
        Type = bufferType;
        Pixmap = pixmapFormat;
        RawData = new byte[RawDataLength];
    }

    [FieldOffset(0)]
    public BufferType Type;

    [FieldOffset(4)]
    public PixmapFormat Pixmap;

    [FieldOffset(4)]
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=RawDataLength)]
    public byte[] RawData;

    public const int RawDataLength = 200;
}

[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct PixmapFormat
{
    public PixmapFormat(uint width, uint height, PixelFormatCode pixelFormat)
    {
        Width = width;
        Height = height;
        PixelFormat = pixelFormat;
        Field = Video4Linux.BufferField.Any;
        BytesPerLine = 0;
        SizeImage = 0;
        Colorspace = Video4Linux.PixelColorspace.None;
        Private = 0;
    }

    public UInt32 Width;

    public UInt32 Height;

    public PixelFormatCode PixelFormat;

    public BufferField Field;

    public UInt32 BytesPerLine;

    public UInt32 SizeImage;

    public PixelColorspace Colorspace;

    public UInt32 Private;
}

最后,这里是调用 ioctl 的方法:

public static void ControlGetFormat(IntPtr fd, BufferType pixmapType, out PixmapFormat pixmapFormat)
{
    if (fd == IntPtr.Zero)
        throw new ArgumentException("invalid file descriptor", "fd");

    Format format = new Format(pixmapType);

    int result = IoCtrlGetFormat(fd, GetFormat.ControlCode, ref format);

    if (result < 0)
        ThrowExceptionOnError();

    pixmapFormat = format.Pixmap;
}

private static readonly IoCtrlRequest GetFormat = new IoCtrlRequest(IoCtrlDirection.Read | IoCtrlDirection.Write, 'V', 4, typeof(Format));

[DllImport("libc", EntryPoint = "ioctl", SetLastError = true)]
private static extern int IoCtrlGetFormat(IntPtr fd, Int32 code, ref Format argument);

public static void ControlSetFormat(IntPtr fd, BufferType pixmapType, ref PixmapFormat pixmapFormat)
{
    if (fd == IntPtr.Zero)
        throw new ArgumentException("invalid file descriptor", "fd");

    PixmapFormat pixmapFormatCopy = pixmapFormat;
    Format format = new Format(pixmapType, pixmapFormatCopy);

    int result = IoCtrlSetFormat(fd, SetFormat.ControlCode, ref format);

    if (result < 0)
        ThrowExceptionOnError();

    pixmapFormat = format.Pixmap;
}

private static readonly IoCtrlRequest SetFormat = new IoCtrlRequest(IoCtrlDirection.Read | IoCtrlDirection.Write, 'V', 5, typeof(Format));

[DllImport("libc", EntryPoint = "ioctl", SetLastError = true)]
private static extern int IoCtrlSetFormat(IntPtr fd, Int32 code, ref Format argument);

最佳答案

问题已通过强制结构大小为实际大小(204,在我的例子中)解决,并删除数组字段 RawData(如 David Heffernan 所建议) ).

确实:

[StructLayout(LayoutKind.Explicit, Pack = 4, CharSet = CharSet.Ansi, Size = 204)]
public struct Format
{
    public Format(BufferType bufferType)
    {
        Type = bufferType;
        Pixmap = new PixmapFormat();
    }

    public Format(BufferType bufferType, PixmapFormat pixmapFormat)
    {
        Type = bufferType;
        Pixmap = pixmapFormat;
    }

    [FieldOffset(0)]
    public BufferType Type;

    [FieldOffset(4)]
    public PixmapFormat Pixmap;
}

当然,Marshal.SizeOf(typeof(Format)) == 204

关于C# 联合结构编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972740/

相关文章:

c# - 仅当记录不存在时才通过存储过程从 TVP 列表中插入项目 - 性能低下

c# - 从 Docker 中的另一个微服务调用微服务

c# - 我可以在 Xamarin Forms 中创建样式主题吗?

python - 使用 Python 修改 WAV 文件

c# - 如何在 C# 代码中使用传递给回调的 C/C++ native 结构

xml - JAXB 是否可以首先通过包含进行编码(marshal),然后通过 @XmlIDREF 进行编码(marshal)以供后续引用?

.net - 使用 P/Invoke 编码结构时如何忽略字段

c# - 是否有 SSLStream 以外的 C# 安全套接字?

c# - 有趣的 LinqToSql 行为

linux - 使用 MPI.NET 和 Mono 框架在 super 计算机的 linux 节点上执行分布式计算