我正在开发一个需要与 Video4Linux 抽象交互的应用程序。该应用程序是用 C# 开发的,使用 mono 框架。
我面临的问题是我无法 P/Invokeioctl
系统调用。或者,更准确地说,我可以 P/Invoke 它,但它崩溃得很厉害。
外部声明如下:
[DllImport("libc", EntryPoint = "ioctl", SetLastError = true)]
private extern static int KernelIoCtrl(int fd, int request, IntPtr data);
到现在为止还挺好。
使用的实际例程KernelIoCtrl
如下:
protected virtual int Control(IoSpecification request, object data)
{
GCHandle dataHandle;
IntPtr dataPointer = IntPtr.Zero;
try {
// Pin I/O control data
if (data != null) {
dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
dataPointer = dataHandle.AddrOfPinnedObject();
}
// Perform I/O control
int result = KernelIoCtrl(mFileDescriptor, request.RequestCode, dataPointer);
int errno = Marshal.GetLastWin32Error();
// Throw exception on errors
if (errno != (int)ErrNumber.NoError)
throw new System.ComponentModel.Win32Exception(errno);
return (result);
} finally {
if (dataPointer != IntPtr.Zero)
dataHandle.Free();
}
}
上面所有的代码看起来都不错。该类IoSpecification
用于计算遵循标头规范的 I/O 请求代码(基本上它遵循_IOC
在/usr/include/linux/asm/ioctl.h
.
参数是一个结构体data
,声明如下:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Capability
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string Driver;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Device;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string BusInfo;
public UInt32 Version;
public CapabilityFlags Capabilities;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
public UInt32[] Reserved;
}
它应该模仿以下结构(在 声明/usr/include/linux/videodev2.h
):
struct v4l2_capability {
__u8 driver[16]; /* i.e. "bttv" */
__u8 card[32]; /* i.e. "Hauppauge WinTV" */
__u8 bus_info[32]; /* "PCI:" + pci_name(pci_dev) */
__u32 version; /* should use KERNEL_VERSION() */
__u32 capabilities; /* Device capabilities */
__u32 reserved[4];
};
在发生崩溃之前,IOCTL 请求代码计算存在问题,并且KernelIoCtrl
按预期工作(返回errno
等于EINVAL)。当我纠正错误(并且确实具有正确的 IOCTRL 请求代码)时,调用已开始导致崩溃。
总之,结构编组似乎存在问题,但我看不出它出了什么问题。
我担心问题出在变量参数列表上,因为ioctl例程声明如下(取自 man):
int ioctl(int d, int request, ...);
但是我看到很多代码将上述例程声明为int ioctl(int d, int request, void*);
,并且我可以确保特定的 IOCTRL 请求只接受一个参数。