CStr for Pascal


Author: Dave
Date: 03.20.14 - 1:02am



One thing I love about vb6 is that it does a lot of repetitive things for you, such as auto converting variables where it makes sense. This frees you from having to deal with minutia.

In VB6 the following is perfectly valid: str = "Found: " & intCount & " instances"

In Pascal this requires: str := 'Found: ' + IntToStr(intCount) + ' instances';

VB6 has the universal CStr() to convert any var type to string, In Pascal each type has their own conversion method.

Below is a universal CStr() function for pascal that also includes support for arrays (unlike the VB6 counterpart).

function CStr(v:Variant):string;
var
  vs: variant;
  ret: string;
  a: integer;
  b: integer;
begin
        try
           if VarIsArray(v) then begin
              a := VarArrayLowBound(v,1);
              b := VarArrayHighBound(v, 1);
              while a <= b do
              begin
                  VarCast(vs,v[a],varString);
                  ret += VarToStr(vs);
                  if a <> b then ret += ', ';
                  inc(a);
              end;
              Result := '[' + ret + ']';
              exit;
           end;
           VarCast(vs,v,varString);
           Result := VarToStr(vs);
        except on E: Exception do
           Result := E.Message;
        end;
end;    

Example Use:

uses
   Variants ...

var
  v: variant; 

begin
  WriteLn('boolean test: ' + cstr(true));
  WriteLn('int test: ' + cstr(32));
  WriteLn('str test: ' + cstr('this is my string'));

  v := VarArrayCreate([0, 9], varInteger);
  for i := 0 to 9 do v[i]:= i;
  WriteLn('test: ' + cstr(v));
  VarClear(v);

  v := VarArrayCreate([0, 3], varOleStr );
  for i := 0 to 3 do v[i]:= StringOfChar( chr(i+$41), 5) ;
  WriteLn('test 2: ' + cstr(v));
  VarClear(v); 





Comments: (0)

 
Leave Comment:
Name:
Email: (not shown)
Message: (Required)
Math Question: 11 + 19 = ? followed by the letter: E 



About Me
More Blogs
Main Site
Posts: (All)
2020 ( 2 )
2019 ( 5 )
2018 ( 6 )
2017 ( 6 )
2016 ( 22 )
2015 ( 16 )
2014 (25)
     Query Last 12 Mos
     Progid from Interface ID
     VB6 to C Array Examples
     Human Readable Variant Type
     ScriptBasic COM Integration
     CodeView Addin
     ScriptBasic - Part 2
     Script Env
     MSCOMCTL Win7 Error
     printf override
     History Combo
     Disable IE
     API Hooking in VB6
     Addin Hook Events
     FastBuild Addin
     VB6 MemoryWindow
     Link C Obj Files into VB6
     Vb6 Standard Dlls
     CStr for Pascal
     Lazarus Review
     asprintf for VS
     VB6 GlobalMultiUse
     Scintilla in VB6
     Dynamic Highlight
     WinVerifyTrust, CryptMsgGetParam VB6
2013 ( 4 )
2012 ( 10 )
2011 ( 7 )
2010 ( 11 )
2009 ( 3 )