gpt4 book ai didi

C# - 可以使用 IOCTL

转载 作者:行者123 更新时间:2023-11-30 19:33:49 26 4
gpt4 key购买 nike

我正在尝试为允许“现金抽屉”附件的销售点系统编写代码。打开现金抽屉的手册中提供了代码(使用 IOCTL 在 C++ 中)。由于我在 C# .NET 中编码,是否可以在 C# 中执行类似的操作,或者我是否必须编写一些非托管代码?

我能否从 C# 中获取“\\.\ADVANSYS”的句柄?我需要使用 DLLImport 吗?

如果有人能指出正确的方向,我将不胜感激。

// IOCTL Codes
#define GPD_TYPE 56053
#define ADV_OPEN_CTL_CODE CTL_CODE(GPD_TYPE, 0x920, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define ADV_STATUS_CTL_CODE CTL_CODE(GPD_TYPE, 0x900, METHOD_BUFFERED, FILE_ANY_ACCESS)
void OpenDrawer(UCHAR uWhichDrawer) // uWhichDrawer = 1 => CD#1, uWhichDrawer = 2 => CD#2
{
HANDLE hFile;
BOOL bRet
UCHAR uDrawer = uWhichDrawer;

// Open the driver
hFile = CreateFile(TEXT("\\\\.\\ADVSYS"),
GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

if (m_hFile == INVALID_HANDLE_VALUE)
{
AfxMessageBox("Unable to open Cash Drawer Device Driver!");
return;
}

// Turn on the Cash Drawer Output (Fire the required solenoid)
bRet = DeviceIoControl(hFile, ADV_CD_OPEN_CTL_CODE,
&uDrawer, sizeof(uDrawer),
NULL, 0,
&ulBytesReturned, NULL);

if (bRet == FALSE || ulBytesReturned != 1)
{
AfxMessageBox("Failed to write to cash drawer driver");
CloseHandle(hFile);
return;
}
CloseHandle(hFile);
}

最佳答案

C++ 错误百出,不确定我是否正确。最好的办法是使用更改后的参数类型声明 DeviceIoControl(),以便于调用。您还必须 P/Invoke CreateFile 因为 FileStream 无法打开设备。它应该看起来像这样:

using System;
using System.IO;
using System.ComponentModel;
using System.Runtime.InteropServices;

class Program {
static void Main(string[] args) {
IntPtr hdl = CreateFile("\\\\.\\ADVSYS", FileAccess.ReadWrite,
FileShare.None, IntPtr.Zero, FileMode.Open,
FileOptions.None, IntPtr.Zero);
if (hdl == (IntPtr)(-1)) throw new Win32Exception();
try {
byte drawer = 1;
bool ok = DeviceIoControl(hdl, CTLCODE, ref drawer, 1, IntPtr.Zero,
0, IntPtr.Zero, IntPtr.Zero);
if (!ok) throw new Win32Exception();
}
finally {
CloseHandle(hdl);
}
}
// P/Invoke:
private const uint CTLCODE = 0xdaf52480;
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CreateFile(string filename, FileAccess access,
FileShare sharing, IntPtr SecurityAttributes, FileMode mode,
FileOptions options, IntPtr template
);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool DeviceIoControl(IntPtr device, uint ctlcode,
ref byte inbuffer, int inbuffersize,
IntPtr outbuffer, int outbufferSize,
IntPtr bytesreturned, IntPtr overlapped
);
[DllImport("kernel32.dll")]
private static extern void CloseHandle(IntPtr hdl);
}

关于C# - 可以使用 IOCTL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2871428/

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