zoukankan      html  css  js  c++  java
  • delphi 给字符指针分配内存

    今天,对接第三方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;
    
  • 相关阅读:
    155. 最小栈
    160. 相交链表
    PAT 1057 Stack
    PAT 1026 Table Tennis
    PAT 1017 Queueing at Bank
    PAT 1014 Waiting in Line
    PAT 1029 Median
    PAT 1016 Phone Bills
    PAT 1010 Radix
    PAT 1122 Hamiltonian Cycle
  • 原文地址:https://www.cnblogs.com/lodor/p/6646875.html
Copyright © 2011-2022 走看看