用API寫了個VB6 的類mycomm(環境是WinXP2 + VB6 sp6 rev6.0.9782),在Sub Main()讀寫串口下一切正常!不管是調試,還是編譯運行都好好的。
將這個類加入到一個現有的、帶有窗體的VB6工程中後,運行程序,讀寫串口絕大時候都正常!
可是就在退出程序時十次有七八次都(不是總是)出現“遇到問題需要關閉。我們對此引起的不便表示抱歉”這樣的錯誤。
如果將調用mycomm的代碼注釋後,再運行就沒問題了。
網上找了一天,沒解決。結果今天自己搞定了,HOHO!
原來是在類初始化時用 GlobalAlloc();類終止時用了 GlobalFree() 引起的!
不用這個方法,改成定義動態數組就可以了。如:
Private m_buffIn() As Byte
相關的API聲明中參數類型改成Byte:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Byte, Source As Byte, ByVal length As Long)
Private Declare Function WriteFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Byte, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, lpOverlapped As Any) As Long
Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Byte, ByVal nNumberOfBytesToRead As Long, lpnBytesRead As Long, lpOverlapped As Any) As Long
調用時形如:
Redim m_buffIn(0 to 1024)
Call CopyMemory(buffInput(0), m_buffIn(0), nBytesRead)
附:之前還遇到過下面的錯誤(出自http://hi.csdn.Net/tipfoo):
“0x????????”指令引用的“0xc0000005”內存。該內存不能為“read”。
“0x????????”指令引用的“0x????????”內存,該內存不能為“written”。
解決:傳遞的字符串參數值末尾加 Chr(0)。