Delphi How can i find a resource name from resourcestring unit

前端 未结 2 1669
慢半拍i
慢半拍i 2020-12-12 03:17

The situation is:

unit abc;

interface

resourcestring
  aabbcc = \'my text here\';

implementation

end.

From my application I received er

2条回答
  •  不知归路
    2020-12-12 03:57

    I imagine you're asking for a function with the following signature and behavior:

    function GetNamedResourceString(const Name: string): string;
    
    Assert(GetNamedResourceString('aabbcc') = 'my text here');
    

    Resource strings are stored in your program in a string-table resource, where each string has a numeric index. The named identifier you use in your program is not kept anywhere at run time. Therefore, there is no built-in way to take the text 'aabbcc' and discover which string resource it's associated with.

    However, there is a way to take the Delphi resourcestring identifier in your code and discover its numeric ID. Type-cast the expression @aabbcc to PResStringRec, and then read its Identifier field. Look at LoadResString in System.pas to see how the RTL uses this information.

    You could use the PResStringRec values to build a TDictionary at run time, and then use that dictionary in implementing the hypothetical GetNamedResourceString function outlined above.

    NamedResources := TDictionary.Create;
    NamedResources.Add('aabbcc', PResStringRec(@aabbcc));
    
    function GetNamedResourceString(const Name: string): string;
    begin
      Result := LoadResString(NamedResources[Name]);
    end;
    

    If I were doing this for a real project, I would probably use a pre-build script to parse an input file to automatically generate the calls to NamedResources.Add from the corresponding resourcestring declarations.

提交回复
热议问题