我正在尝试通过P / Invoke将数据写入串行端口(显然不是使用SerialPort类).这是我到目前为止所拥有的:
[DllImport("kernel32", SetLastError = true)]
static extern IntPtr CreateFile(string filename, // file name
uint desiredAccess, // read? write?
uint shareMode, // sharing
uint attributes, // SecurityAttributes pointer
uint creationDisposition,
uint flagsAndAttributes,
uint templateFile);
[DllImport("kernel32", SetLastError = true)]
static extern bool WriteFile(IntPtr hFile, // handle to file
byte[] lpBuffer, // data buffer
uint nBytesToWrite, // number of bytes to write
out uint nBytesWritten, // number of bytes written
[In] ref NativeOverlapped overlapped); // overlapped buffer
const uint OPEN_EXISTING = 3;
_portHandle = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
uint bytesWritten;
var buffer = Encoding.ASCII.GetBytes("foo\r");
var overlapped = new NativeOverlapped();
WriteFile(_portHandle, buffer, (uint)buffer.Length, out bytesWritten, ref overlapped);
我得到一个_portHandle!= -1并且可以调用WriteFile.但是在通话结束后,它什么也没做.我可以在VS-debug模式下永远等待并等待调用返回.此外,没有抛出任何异常.
有任何kernel32.dll主人可以帮助我吗?
最佳答案 感谢Papa Mufflon介绍这个可用的项目,我为自己派生了这个,并从
https://github.com/ebraminio/PInvokeSerialPort开始制作非常简单的开源项目,你也可以从
https://nuget.org/packages/PInvokeSerialPort下载它.
当然这个项目还不完整,所以任何建议任何要求的功能对我来说都很有价值:)