您的位置:首页 > 编程语言 > Delphi

delphi 给字符指针分配内存

2017-03-30 16:35 537 查看
今天,对接第三方dll的时候出现如下问题:

接口声明如下:

long BL_tradeBalance (char *MerchantNumber,char *PosId,char *OperatorNumber,

int TypeCode,int PrintMode,

char *ResponseBuf,char *retCode,char *retMsg)

输入参数

char mMerchantNumber[6] //商户号(门店号)

char mPosId[3] //pos机号(终端号)

char mOperatorNumber[20]; //操作员号

int TypeCode; //业态标识 1

int PrintMode; //打印模式 1

输出参数

char ResponseBuf[2048] //f返回当日对账明细

char retCode [20] //返回码

char retMsg [256] //返回信息

----------------------------------------------------------------------------------------

delphi端调用

var

resBuf,retCode,retMsg: PChar;

调用:

dev.BL_tradeBalance(Pchar(sStoreNo),PChar(FPosNo),PChar(FEmpCode),1,1,resBuf,retCode,retMsg)

报dll异常

此时需要我们给返回的指针主动分配内存

resBuf := StrAlloc(2048);
retCode := StrAlloc(20);
retMsg := StrAlloc(256);

如果不是对接方主动说明,一般需要我们主动给返回值分配内存,然后做好释放工作

--------------------------------------------------------------------------------

resBuf := StrAlloc(2048);
retCode := StrAlloc(20);
retMsg := StrAlloc(256);
try

....

finally

StrDispose(resBuf);
StrDispose(retCode);
StrDispose(retMsg);

end;

--------------------------------------------------------------------------------

扩展了解下字符指针内存分配函数

GetMem
AllocMem
ReallocMem
FreeMem

GetMemory
ReallocMemory
FreeMemory

New
Dispose

NewStr
DisposeStr

StrNew
StrAlloc
StrDispose

给字符指针(PChar、PWideChar、PAnsiChar)分配内存, 最佳选择是: StrAlloc.

StrAlloc 虽然最终也是调用了 GetMem, 但 StrAlloc 会在指针前面添加 Delphi 需要的 4 个管理字节(记录长度).

StrAlloc 分配的内存, 用 StrDispose 释放, 用 StrBufSize 获取大小.

用 FreeMem 释放可以吗? 这样会少释放 4 个字节.

这种类型的指针一般用于 API 函数的参数, 譬如获取窗口标题:


var
p: PChar;
begin
p := StrAlloc(256);
GetWindowText(Handle, p, StrBufSize(p));
ShowMessage(p); {Form1}
StrDispose(p);
end;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: