P / Invoke呼叫刚刚停止

时间:2010-12-04 11:53:32

标签: c# pinvoke kernel32 writefile

我正在尝试通过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主人都有帮助吗?

2 个答案:

答案 0 :(得分:2)

感谢Papa Mufflon介绍这个可用的项目,我为自己派生了这个项目并从https://github.com/ebraminio/PInvokeSerialPort创建了一个非常简单的开源项目,您也可以从https://nuget.org/packages/PInvokeSerialPort下载它。

当然这个项目还没有完成,所以对我提出任何要求的任何建议都对我有价值:)

答案 1 :(得分:0)

从John Hind(http://msdn.microsoft.com/en-us/magazine/cc301786.aspx)获取Serial Comm,而不是开发自己的:)

效果很好!