求教:access violation错误
本人现在用Delphi2009.
网上找的一个基于Delphi7的方法:获取打印机端口列表。
在运行到下面两句时报access violation错误
//第一次循环时报错,result有create
result.Add(pPortInfo^.pPortName+'|'+pPortInfo^.pDescription);
//第一次循环时赋值成功,第二次循环时报错,
dddd:=pPortInfo^.pPortName+'|'+pPortInfo^.pDescription;
完整函数代码如下:
Function GetPrinterPort():TStringList;
Var
pBuffer : Pointer; // pointer to buffer memory
pPortInfo : PPortInfo2; // pointer to a PORT_INFO_2 record
dwLastError, // last error (-> GetLastError())
dwNumBytes, // [needed] size of buffer
dwNumPortInfos : DWORD; // number of port info records in list
dddd:String;
Begin
result := TStringList.Create;
If (EnumPorts(Nil {Nil -> local PC},2,Nil,0,dwNumBytes,dwNumPortInfos) <> TRUE) Then
Begin
dwLastError := GetLastError();
If (dwLastError <> ERROR_INSUFFICIENT_BUFFER) Then
Begin
MessageDlg(SysErrorMessage(GetLastError()), mtCustom, [mbOK], 0);
End
Else
Begin
GetMem(pBuffer, dwNumBytes);
Try
If (EnumPorts(Nil,2,pBuffer,dwNumBytes,dwNumBytes,dwNumPortInfos) <> TRUE) Then
Begin
MessageDlg(SysErrorMessage(GetLastError()), mtCustom, [mbOK], 0);
End
Else
Begin
pPortInfo := PPortInfo2(pBuffer);
While (dwNumPortInfos > 0) Do
Begin
//第一次循环时报错
result.Add(pPortInfo^.pPortName+'|'+pPortInfo^.pDescription);
//第二次循环时报错
dddd:=pPortInfo^.pPortName+'|'+pPortInfo^.pDescription;
Inc(pPortInfo);
Dec(dwNumPortInfos);
End;
End;
Finally
FreeMem(pBuffer);
End;
End;
End
Else
Begin
MessageDlg('no ports present !', mtCustom, [mbOK], 0);
End;
End;