求教:access violation错误

woolnil 2016-03-22 07:25:03
本人现在用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;
...全文
264 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

16,747

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧