Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Built in XPVista Random Number Generator

Title: Built in XP/Vista Random Number Generator Question: Having a second source of random numbers can be useful. Windows, since XP has included a lightweight random number generator. Answer: The built in routine RTLGenRandom is part of the advapi32.dll and can be called directly. The code below populates a buffer by loading the dll dynamically. It is a translation of the code from http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx Change the buffer size to suit yourself. How It works The buffersize is passed into Initialise which loads the advapi32.dll and tries to find SystemFunction036. If it finds it, the function is called and populates the buffer with buffersize random values in the range 0..255. This should also work in Vista and may work in Delphi 3. Only tested in d4. var buff : array[1..32] of byte; type tpfn = function ( var P;c : cardinal): boolean; stdcall; function Initialise(buffersize:cardinal):boolean; var hlib : Hmodule; pfn : tpfn; begin result := false; hLib:=LoadLibrary('ADVAPI32.DLL'); pfn=nil; if (hLib 0) then begin pfn := GetProcAddress(hLib,'SystemFunction036'); end; fillchar(buff,buffersize,#0); if (assigned(pfn)) then begin result := pfn(buff,Buffersize); end; if (hlib 0) then FreeLibrary(hlib); end;