Wednesday, March 31, 2021

Calculating hashes: MD2, MD4, MD5, SHA1, SHA2-256, SHA2-384, and SHA2-512

It works with MD2, MD4, MD5, SHA1, SHA2-256, SHA2-384, and SHA2-512. Put the below code in a module (BAS file). It does everything that CAPICOM does regarding hashes, but without using any ActiveX DLL files. It depends entirely on the standard cryptographic API DLL files, using declare statements. There are several publicly accessible functions. These are
HashBytes
HashStringA
HashStringU
HashArbitraryData
BytesToHex
BytesToB64

HashBytes computes a hash of a 1D byte array, who's lower bound is 0.

HashStringA computes the hash of an Ascii/Ansi (1 byte per character) string. As VB6 strings are actually Unicode (2 bytes per character), and due to the fact that this function is intended to calculate the hash of the Ascii version of the string, the function first converts VB6's unicode characters to true Ascii characters via VB6's StrConv function. However, because characters with an Ascii value above 127 will differ between locales, the LocaleID is needed to be known for this conversion. As such, LocaleID is a parameter for this function. By default, the LocaleID used by the program is the LocaleID of the PC that the program is running on. This should be used in most situations, as this will generate a hash that will match the output of most other programs that generate a hash (such as the program called Easy Hash).

HashStringU computes the hash of a Unicode (2 bytes per character) string. As VB6 strings are actually Unicode, there is no conversion needed, and thus is no need to specify LocaleID. Therefore, this function doesn't have a LocaleID parameter. Because each character is defined by 2 bytes, rather than 1, the output of this hash function will obviously differ from the hash calculated by HashStringA, and thus will differ from the hash calculated by most other hash calculating programs (such as the freeware one that I used for testing called Easy Hash). For example, a string with 3 spaces " " is represented as the byte array (shown in hex) 20 00 20 00 20 00 in Unicode encoding, but as 20 20 20 in Ascii encoding. These are 2 distinctly different byte arrays, and thus will produce 2 completely different hashes.
Side-Note regarding Unicode in VB6: Despite this fact, that internally in VB6 all the strings are Unicode, the implementation of Unicode in VB6 is VERY LIMITED. That is, it won't display any Unicode character that can't also be displayed as an extended ascii character for the computer's current locale. Instead it will show it as a question mark. This won't effect how this function works (or the above function, as it's computing a hash, not displaying anything), but it will effect whether or not a given string will be properly displayed.

HashArbitraryData computes the hash of absolutely anything. It just needs to know where in memory the first byte of data is, and how many bytes long the data is. It will work with multidimensional byte arrays, arrays of other data types, arrays that start with with a lower bound other than zero, user defined types, sections of memory allocated with API functions, etc. There's nothing that it can't compute the hash of. Of course this gives you the added responsibility of needing to know where exactly in memory the data is, and the size of the data in bytes.

BytesToHex. This is a function intended to convert the raw bytes output from a hash function to a displayable hexadecimal string.

BytesToB64. This is a function intended to convert the raw bytes output from a hash function to a displayable base64 string.

Code:

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)
 
Private Declare Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" (ByRef phProv As Long, ByVal pszContainer As String, ByVal pszProvider As String, ByVal dwProvType As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptCreateHash Lib "advapi32.dll" (ByVal hProv As Long, ByVal Algid As Long, ByVal hKey As Long, ByVal dwFlags As Long, ByRef phHash As Long) As Long
Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hHash As Long, ByRef pbData As Any, ByVal dwDataLen As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptGetHashParam Lib "advapi32.dll" (ByVal hHash As Long, ByVal dwParam As Long, ByRef pByte As Any, ByRef pdwDataLen As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptDestroyHash Lib "advapi32.dll" (ByVal hHash As Long) As Long
Private Declare Function CryptReleaseContext Lib "advapi32.dll" (ByVal hProv As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptBinaryToString Lib "Crypt32.dll" Alias "CryptBinaryToStringA" (ByRef pbBinary As Any, ByVal cbBinary As Long, ByVal dwFlags As Long, ByVal pszString As String, ByRef pcchString As Long) As Long
 
Private Const PROV_RSA_AES As Long = 24
Private Const CRYPT_VERIFYCONTEXT As Long = &HF0000000
 
Public Enum HashAlgo
    HALG_MD2 = &H8001&
    HALG_MD4 = &H8002&
    HALG_MD5 = &H8003&
    HALG_SHA1 = &H8004&
    HALG_SHA2_256 = &H800C&
    HALG_SHA2_384 = &H800D&
    HALG_SHA2_512 = &H800E&
End Enum
 
Private Const HP_HASHSIZE As Long = &H4&
Private Const HP_HASHVAL As Long = &H2&
 
 
Public Function HashBytes(ByRef Data() As Byte, Optional ByVal HashAlgorithm As HashAlgo = HALG_MD5) As Byte()
Dim hProv As Long
Dim hHash As Long
Dim Hash() As Byte
Dim HashSize As Long
 
CryptAcquireContext hProv, vbNullString, vbNullString, 24, CRYPT_VERIFYCONTEXT
CryptCreateHash hProv, HashAlgorithm, 0, 0, hHash
CryptHashData hHash, Data(0), UBound(Data) + 1, 0
CryptGetHashParam hHash, HP_HASHSIZE, HashSize, 4, 0
ReDim Hash(HashSize - 1)
CryptGetHashParam hHash, HP_HASHVAL, Hash(0), HashSize, 0
CryptDestroyHash hHash
CryptReleaseContext hProv, 0
 
HashBytes = Hash()
End Function
 
 
 
Public Function HashStringA(ByVal Text As String, Optional ByVal LocaleID As Long, Optional ByVal HashAlgorithm As HashAlgo = HALG_MD5) As Byte()
Dim Data() As Byte
Data() = StrConv(Text, vbFromUnicode, LocaleID)
HashStringA = HashBytes(Data, HashAlgorithm)
End Function
 
Public Function HashStringU(ByVal Text As String, Optional ByVal HashAlgorithm As HashAlgo = HALG_MD5) As Byte()
Dim Data() As Byte
Data() = Text
HashStringU = HashBytes(Data, HashAlgorithm)
End Function
 
Public Function HashArbitraryData(ByVal MemAddress As Long, ByVal ByteCount As Long, Optional ByVal HashAlgorithm As HashAlgo = HALG_MD5) As Byte()
Dim Data() As Byte
ReDim Data(ByteCount - 1)
CopyMemory Data(0), ByVal MemAddress, ByteCount
HashArbitraryData = HashBytes(Data, HashAlgorithm)
End Function
 
 
 
 
Public Function BytesToHex(ByRef Bytes() As Byte) As String
Dim HexStringLen As Long
Dim HexString As String
 
CryptBinaryToString Bytes(0), UBound(Bytes) + 1, 12, vbNullString, HexStringLen
HexString = String$(HexStringLen, vbNullChar)
CryptBinaryToString Bytes(0), UBound(Bytes) + 1, 12, HexString, HexStringLen
 
BytesToHex = UCase$(HexString)
End Function
 
Public Function BytesToB64(ByRef Bytes() As Byte) As String
Dim B64StringLen As Long
Dim B64String As String
 
CryptBinaryToString Bytes(0), UBound(Bytes) + 1, 1, vbNullString, B64StringLen
B64String = String$(B64StringLen, vbNullChar)
CryptBinaryToString Bytes(0), UBound(Bytes) + 1, 1, B64String, B64StringLen
 
BytesToB64 = B64String
End Function

Source:
http://earlier189.rssing.com/browser.php?indx=6373759&item=379

Tuesday, March 30, 2021

How to insert machine code in source code: VB6 & ASM

Just a quick post for documentation sake of using inline asm with VB6 (or at least as close as we can get to it without an external c dll. In terms of development of the asm to put in. You can use your C Compiler to generate it for you..here are the tips.

  • CallwindowsProc has 5 arguments max and can return a long The first argument is already used so your args start at [EBP+0x0C] this means use a dummy int arg first in your prototype to line up args.
  • do not use any sub functions from your code do things in blocks in you have to.
  • once you generate your code, you can extract the opcodes from VC in debug mode viewing mixed mode disasm (develop as an exe usually although you may have to as a dll to use with vb as standard call dll).
  • you need to strip all the function prolog and epilog asm from the compiler generated block (or use naked declspec) your ret should be RETN 10h.
  • keep a couple nops (&H90) in place at start in case you need room to add a breakpoint (&hCC) manually to stop on your asm in a debugger to debug it. yes you will have to use ollydbg to debug it in asm most likley.
  • you can twiddle with the CallWindowProc prototypes more based on what you are using it for..see last example.
Full example here:


Note: All single quotes for comments are stripped by my blog script. Same as default CallWindowProc except param 1 is now "ByRef lpBytes As Any" or you can use the default like this: CallWindowProc(Varptr(asmBytes(0)).


The most simple and direct example of VB6 & ASM:

Private Declare Function CallAsm Lib "user32" 
    Alias "CallWindowProcA" _
    (ByRef lpBytes As Any, 
    ByVal hWnd As Long, 
    ByVal Msg As Long, 
    ByVal wParam As Long, 
    ByVal lParam As Long) As Long

Function Shl(x As Long) As Long
    '8B45 0C        MOV EAX,DWORD PTR SS:[EBP+12]
    'D1E0           SHL EAX,1
    'C2 10 00       RETN 10h
    Dim o() As Byte
    Const sl As String = "8B 45 0C D1 E0 C2 10 00"
    o() = toBytes(sl)
    Shl = CallAsm(o(0), x, 0, 0, 0)
End Function

private Function toBytes(x As String) As Byte()
    Dim tmp() As String
    Dim fx() As Byte
    Dim i As Long
    
    tmp = Split(x, " ")
    ReDim fx(UBound(tmp))
    
    For i = 0 To UBound(tmp)
        fx(i) = CInt("&h" & tmp(i))
    Next
    
    toBytes = fx()

End Function

Another example of working on a byte buffer in your asm:

Private Declare Function CallAsm2 Lib "user32" 
     Alias "CallWindowProcA" _
    (ByRef lpBytes As Any, 
     ByRef chararray As Any, 
     ByVal length As Long, 
     ByVal unused1 As Long, 
     ByVal unused2 As Long) As Long




Const opcodes As String = 
   "909090C745F800000000EB098B4DF88" & _
   "3C101894DF88B55F83B55107D258B45" & _
   "0C0345F88A08884DFC8B45F833D28A5" & _
   "5FC2AD08855FC8B550C0355F88A45FC" & _
   "8802EBCA9090C21000"

fx() = toBytes2(opcodes)
CallAsm2 fx(0), byteBufferToWorkOn(0), UBound(byteBufferToWorkOn), 0, 0

Function toBytes2(x As String, Optional debugit As Boolean = False) As Byte()
    Dim tmp() As String
    Dim fx() As Byte
    Dim i As Long
    Dim y
    
    ReDim fx(Len(x) / 2)
    
    For i = 1 To Len(x) Step 2
        fx(y) = CByte(CLng("&h" & Mid(x, i, 2)))
        y = y + 1
    Next
    
    If debugit Then fx(0) = &HCC
    
    toBytes2 = fx()
    
End Function

The opcodes are for the following C with the prolog and epilog stripped out:

void __stdcall  fnDecode(int dummy, char* b, int len)
{
    char x;
    for(int i=0; i<len; i++){
        x = b[i];
        _asm{
            //do stuff to x here
        }
        b[i] = x; //update vb byte buffer
    }
} 

Source:
http://sandsprite.com/blogs/index.php/index.php?uid=11&pid=43

Wednesday, February 17, 2021

String-style operations by wrapping a Byte array


People seem to get tangled up in their underwear a lot trying to fiddle with binary data in String variables. Often they run into nightmares where they convert Unicode "to Unicode" and then back later, in the vain hope of avoiding data corruption. And then some locale boundary gets crossed and it all falls down. Hard.

From what I've seen the bulk of this comes from the desire to use String operations on binary data. But most of these are fairly trivial to synthesize, especially with the help of CopyMemory.

The Bytarr Class wraps a dynamic Byte array along with several properties and methods to make this easier.

You can use the Class for lots of applications, or when you only need one or two operations it can server as a template for inline code when you don't want the Class.

Bytarr (biter?) is bundled with a test program in the attachment. This also includes my Dump Class, which I find handy for debugging and testing.



Source:

Sunday, February 14, 2021

Working with pointers - VB6 (by Krivous Anatoly Anatolevich)

Often there are situations when you need to get data having only the address (for example, in WndProc, HookProc). Usually, simply copy the data via CopyMemory the structure after changing data and copy it back. If the structure is large, it will be a waste of resources to copy into structure and back. In languages such as C ++ is all done easily with the help of pointers, written something like newpos = (WINDOWPOS *) lparam. Nominally VB6 does not work with pointers, but there are a few workarounds.

Public Declare Function GetMem4 Lib "msvbvm60" (src As Any, Dst As Any) As Long
Public Declare Function ArrPtr Lib "msvbvm60" Alias "VarPtr" (src() As Any) As Long
For a start I will give the necessary declarations:
Code:

Private Type Vector
    X As Single
    Y As Single
End Type
Private Type TestRec
    Name As String
    Value As Long
    Position As Vector
    Money As Double
End Type
 
Private Sub Form_Load()
    Dim tr As TestRec
    Test tr
End Sub
 
Private Function Test(Pointer As TestRec, Optional ByVal nu As Long)
    Dim q As TestRec, z As TestRec
 
    q.Name = "The trick"
    q.Position.X = 5: q.Position.Y = 15
    q.Value = 12345: q.Money = 3.14
 
    z.Name = "Visual Basic 6.0"
    z.Position.X = 99: z.Position.Y = 105
    z.Value = 7643: z.Money = 36.6
 
    GetMem4 VarPtr(q), ByVal VarPtr(nu) - 4    ' Set pointer to q (Pointer = &q)
 
    PrintRec Pointer
 
    GetMem4 VarPtr(z), ByVal VarPtr(nu) - 4    ' Set pointer to z (Pointer = &z)
 
    PrintRec Pointer
 
End Function
 
Private Sub PrintRec(Pt As TestRec)
    Debug.Print "----------------"
    Debug.Print "Name = " & Pt.Name
    Debug.Print "Value = " & Pt.Value
    Debug.Print "Money = " & Pt.Money
    Debug.Print "Position.X = " & Pt.Position.X
    Debug.Print "Position.Y = " & Pt.Position.Y
End Sub
You can also create a pointer by using arrays. The idea is to create 2 arrays one element each, which will store the address of a variable, and the other will refer to the data. The first will always be Long, a second type of data desired. This is useful for example if you want to pass on lists, etc. It's no secret that the array in VB is simply an SafeArray. In the data structure of this array contains a lot of useful information, and a pointer to the data. What we do, we create two arrays:


  • 1st (with address) refers to a pointer to the second data array. As a result, changing the values in the first array, 2nd automatically refer to the desired data.*
  • 2nd is directly the data pointed to by the first.*


Also, after all the manipulations necessary to return all the pointers back to VB properly clear the memory.* For all manipulations I created auxiliary functions and structure for data recovery.* Address SafeArray is available through Not Not Arr, but IDE after such manipulations are glitches with floating point:
Code:

Public Type PtDat
    Prv1 As Long
    Prv2 As Long
End Type
 
' Create the pointer. 1st param is pointer, 2nd address.
Public Function PtGet(Pointer() As Long, ByVal VarAddr As Long) As PtDat
    Dim i As Long
    i = GetSA(ArrPtr(Pointer)) + &HC
    GetMem4 ByVal i, PtGet.Prv1
    GetMem4 VarAddr + &HC, ByVal i
    PtGet.Prv2 = Pointer(0)
End Function
' Release pointer
Public Sub PtRelease(Pointer() As Long, prev As PtDat)
    Pointer(0) = prev.Prv2
    GetMem4 prev.Prv1, ByVal GetSA(ArrPtr(Pointer)) + &HC
End Sub
' Obtaint address of SafeArray (same Not Not)
Public Function GetSA(ByVal addr As Long) As Long
    GetMem4 ByVal addr, GetSA
End Function
Example of use:
Code:

Private Sub Form_Load()
    Dim pt() As Long, var() As TestRec, prev As PtDat      ' Pointer, references data, release data.
    Dim q As TestRec, z As TestRec                          ' The structures, which we refer
 
    ReDim pt(0): ReDim var(0)
 
    q.Name = "The trick"
    q.Position.X = 5: q.Position.Y = 15
    q.Value = 12345: q.Money = 3.14
 
    z.Name = "Visual Basic 6.0"
    z.Position.X = 99: z.Position.Y = 105
    z.Value = 7643: z.Money = 36.6
 
    prev = PtGet(pt, GetSA(ArrPtr(var)))                    ' Create "pointer"
 
    pt(0) = VarPtr(q)                                      ' Refer to q (pt = &q)
    PrintRec var(0)
    pt(0) = VarPtr(z)                                      ' Refer to z (pt = &z)
    PrintRec var(0)
 
    PtRelease pt, prev                                      ' Release
 
End Sub

Source:
http://earlier189.rssing.com/browser.php?indx=6373759&item=376

Thursday, January 14, 2021

ALGLIB: Numerical analysis and data processing library in VB6 (by Dr. Sergey Bochkanov)

Download from ME
Download from VBForums

102 modules containing several hundred advanced mathematical functions written by Dr. Sergey Bochkanov. Some of the functions, include:
  • Decision forest classifier (regression model)
  • K-means++ clustering
  • Linear discriminant analysis
  • Linear models
  • Logit models
  • Basic neural network operations
  • Neural network ensemble models
  • Neural network training
  • Principal component analysis
  • Ordinary differential equation solver
  • Fast real/complex convolution
  • Fast real/complex cross-correlation
  • Real/complex FFT
  • Real Fast Hartley Transform
  • Adaptive 1-dimensional integration
  • Gauss-Kronrod quadrature generator
  • Gaussian quadrature generator
  • Inverse distance weighting: interpolation/fitting
  • Linear and nonlinear least-squares solvers
  • Polynomial interpolation/fitting
  • Parametric spline interpolation
  • Rational interpolation/fitting
  • 1D spline interpolation/fitting
  • 2D spline interpolation
  • Level 2 and Level 3 BLAS operations
  • Bidiagonal SVD
  • Eigensolvers
  • Sherman-Morrison update of the inverse matrix
  • LDLT decomposition
  • Determinant calculation
  • Random matrix generation
  • Matrix inverse
  • Real/complex QR
  • LQ
  • bi(tri)diagonal
  • Hessenberg decompositions
  • Condition number estimate
  • Schur decomposition
  • Determinant of a symmetric matrix
  • Symmetric inversion
  • Generalized symmetric eigensolver
  • Condition number estimate for symmetric matrices
  • Singular value decomposition
  • LU and Cholesky decompositions
  • ASA bound constrained optimizer
  • Conjugate gradient optimizer
  • Limited memory BFGS optimizer
  • Improved Levenberg-Marquardt optimizer
  • Nearest neighbor search: approximate and exact
  • Dense linear system solver
  • Symmetric dense linear system solver
  • Airy functions
  • Bessel functions
  • Beta function
  • Chebyshev polynomials
  • Dawson integral
  • Elliptic integrals
  • Exponential integrals
  • Fresnel integrals
  • Gamma function
  • Hermite polynomials
  • Incomplete beta function
  • Incomplete gamma function
  • Jacobian elliptic functions
  • Laguerre polynomials
  • Legendre polynomials
  • Psi function
  • Trigonometric integrals
  • Binomial distribution
  • Chi-Square distribution
  • Pearson/Spearman correlation coefficients
  • Hypothesis testing: correlation tests
  • Descriptive statistics: mean
  • variance, etc.
  • F-distribution
  • High quality random numbers generator
  • Hypothesis testing: Jarque-Bera test
  • Hypothesis testing: Mann-Whitney-U test
  • Normal distribution
  • Poisson distribution
  • Hypothesis testing: sign test
  • Student's t-distribution
  • Hypothesis testing: Student's t-test
  • Hypothesis testing: F-test and one-sample variance test
  • Hypothesis testing: Wilcoxon signed rank test.

Original content from Dr. Sergey Bochkanov:

Contents

Introduction
Getting started with ALGLIB
FAQ
AP library description
ALGLIB reference manual

Introduction

Sections

  • ALGLIB license
  • Documentation license
  • Reference Manual and User Guide
  • Acknowledgements

ALGLIB license

ALGLIB is a free software which is distributed under a GPL license - version 2 or (at your option) any later version. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses

Documentation license

This reference manual is licensed under BSD-like documentation license:
Copyright 1994-2009 Sergey Bochkanov, ALGLIB Project. All rights reserved.
Redistribution and use of this document (ALGLIB Reference Manual) with or without modification, are permitted provided that such redistributions will retain the above copyright notice, this condition and the following disclaimer as the first (or last) lines of this file.
THIS DOCUMENTATION IS PROVIDED BY THE ALGLIB PROJECT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ALGLIB PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Reference Manual and User Guide

ALGLIB Project provides two sources of information: ALGLIB Reference Manual (this document) and ALGLIB User Guide.
ALGLIB Reference Manual contains full description of all publicly accessible ALGLIB units accompanied with examples. Reference Manual is focused on the source code: it documents units, functions, structures and so on. If you want to know what unit YYY can do or what subroutines unit ZZZ contains Reference Manual is a place to go. Free software needs free documentation - that's why ALGLIB Reference Manual is licensed under BSD-like documentation license.
Additionally to the Reference Manual we provide you User Guide. User Guide is focused on more general questions: how fast ALGLIB is? how reliable it is? what are the strong and weak sides of the algorithms used? We aim to make ALGLIB User Guide an important source of information both about ALGLIB and numerical analysis algorithms in general. We want it to be a book about algorithms, not just software documentation. And we want it to be unique - that's why ALGLIB User Guide is distributed under less-permissive personal-use-only license.

Acknowledgements

ALGLIB was not possible without the contribution of next open source projects:
  • LAPACK
  • Cephes
  • GNU MP
  • MPFR

Getting started with ALGLIB

Sections

    FAQ

    Sections

    • What version of Visual Basic are the algorithms translated into?
    • Why is the goto operator used in some programs?
    • What is the AP library?
    • Why do some algorithms (for instance, optimization methods) use reverse communication instead of function pointers, delegates and other means of my programming language?
    • What is ALGLIB aimed at?
    • What is the difference between ALGLIB and other similar projects?
    • What is AlgoPascal?

    What version of Visual Basic are the algorithms translated into?

    The algorithms are translated into VBA, but in general are compatible with VB6.

    Why is the goto operator used in some programs?

    In many programming languages there is control operator continue, but it is absent in VB. In AlgoPascal, this operator appears from time to time. The goto operator is used to replace it and go to the next iteration of the cycle.

    What is the AP library?

    AP library is a generic name for a set of libraries in several programming languages performing low-level tasks depending on specific programming languages. The AP library carries out tasks such as working with dynamic one- and multidimensional arrays in languages which do not support this data type, contains implementation of basic linear algebra algorithms, etc. The library is distributed as source codes under GPL 2+ license (GPL 2 or later). The library is attached to the ALGLIB package.

    Why do some algorithms (for instance, optimization methods) use reverse communication instead of function pointers, delegates and other means of my programming language?

    Optimization, integration and other similar methods are united by one common trait. They need to have a way of calculating the meaning of a function defined by the user at a point defined by the method.
    The most convenient way of solving this problem is transferring a function pointer into the module. However bear in mind that ALGLIB package is written using pseudocode that is automatically translated into different programming languages. While each language has its own function pointer analog that is often different from other languages. When the ALGLIB pseudocode was developed, at some point is became clear that adding function pointers in it will be very complex as this feature is implemented differently in every language. This is why reverse communication was chosen as a different kind of solution.

    What is ALGLIB aimed at?

    It is aimed at creating a convenient and efficient multilingual scientific software library.

    What is the difference between ALGLIB and other similar projects?

    The ALGLIB package:
    • is a multilingual project. The main feature of the project is that each algorithm is represented by programs in several languages and the language list is the same for every algorithm. This is the main advantage of the site before other similar collections - one algorithm, several languages, identical functionality in each language.
    • is focused on numerical analysis. There are some other directions in the project but numerical analysis is a priority.
    • is easy to use. To use the ALGLIB package you don't need to learn an unknown programming language, attach additional external libraries or work with an inconvenient interface to a code written in another programming language.

    What is AlgoPascal?

    AlgoPascal is a programming language, designed particularly for this project. The programs, written in this language, are processed by an automatic translator and translated into other programming languages. Almost all ALGLIB source is produced by the AlgoPascal translator.

    AP library description

    Sections

    • Introduction
    • Compatibility
    • Constants
    • Functions
    • Complex numbers operations

    Introduction

    The document describes a VBA version of the AP library. The AP library for VBA contains a basic set of mathematical functions needed to compile ALGLIB package. The library includes the only module ap.bas.

    Compatibility

    This library is developed for VBA only.

    Constants

    MachineEpsilon
    The constant represents the accuracy of machine operations times some small number r>1.
    MaxRealNumberThe constant represents the highest value of the positive real number, which could be represented on this machine. The constant may be taken "oversized", that is real boundary can be even higher.
    MinRealNumber
    The constant represents the lowest value of positive real number, which could be represented on this machine. The constant may be taken "oversized", that is real boundary can be even lower.

    Functions

    Public Function MaxReal(ByVal M1 As Double, ByVal M2 As Double) As Double
    Returns the maximum of two real numbers.
    Public Function MinReal(ByVal M1 As Double, ByVal M2 As Double) As Double
    Returns the minimum of two real numbers.
    Public Function MaxInt(ByVal M1 As Long, ByVal M2 As Long) As Long
    Returns the maximum of two integers.
    Public Function MinInt(ByVal M1 As Long, ByVal M2 As Long) As Long
    Returns the minimum of two integers.
    Public Function ArcSin(ByVal X As Double) As Double
    Returns arcsine (in radians).
    Public Function ArcCos(ByVal X As Double) As Double
    Returns arccosine (in radians).
    Public Function SinH(ByVal X As Double) As Double
    Returns hyperbolic sine.
    Public Function CosH(ByVal X As Double) As Double
    Returns hyperbolic cosine.
    Public Function TanH(ByVal X As Double) As Double
    Returns hyperbolic tangent.
    Public Function Pi() As Double
    Returns the value of π.
    Public Function Power(ByVal Base As Double, ByVal Exponent As Double) As Double
    Returns Base raised to a power of Exponent (introduced for compatibility).
    Public Function Square(ByVal X As Double) As Double
    Returns x2.
    Public Function Log10(ByVal X As Double) As Double
    Returns common logarithm from X.
    Public Function Ceil(ByVal X As Double) As Double
    Returns the smallest integer bigger or equal to X.
    Public Function RandomInteger(ByVal X As Long) As Long
    Returns a random integer between 0 and I-1.
    Public Function Atn2(ByVal Y As Double, ByVal X As Double) As Double
    Returns an argument of complex number X + iY. From interval from -π to π.

    Complex numbers operations

    As there is no operator overloading in Visual Basic 6.0, operations with complex numbers could not be implemented as easy as with built-in data type. Therefore Complex data type is defined in a library. It is a record with two real number fields x and y, and all the operations are performed with the use of special functions implementing addition, multiplication, subtraction and division. An input can be complex or real, and output is complex. These functions are listed below.
    Public Function C_Add(Z1 As Complex Z2 As Complex):Complex
    Public Function C_AddR(Z1 As Complex R As Double):Complex

    Calculate Z1+Z2 or Z1+R.
    Public Function C_Sub(Z1 As Complex Z2 As Complex):Complex
    Public Function C_SubR(Z1 As Complex R As Double):Complex
    Public Function C_RSub(R As Double, Z1 As Complex):Complex

    Calculate Z1-Z2Z1-R or R-Z1.
    Public Function C_Mul(Z1 As Complex Z2 As Complex):Complex
    Public Function C_MulR(Z1 As Complex R As Double):Complex

    Calculate Z1*Z2 or Z1*R.
    Public Function C_Div(Z1 As Complex Z2 As Complex):Complex
    Public Function C_DivR(Z1 As Complex R As Double):Complex
    Public Function C_RDiv(R As Double, Z2 As Complex):Complex

    Calculate Z1/Z2Z1/R or R/Z2. Modulus calculation is performed using so called "safe" algorithm, that could never cause overflow when calculating intermediate results.
    Public Function C_Equal(Z1 As Complex Z2 As Complex):Boolean
    Public Function C_EqualR(Z1 As Complex R As Double):Boolean
    Public Function C_NotEqual(Z1 As Complex Z2 As Complex):Boolean
    Public Function C_NotEqualR(Z1 As Complex R As Double):Boolean

    Compare Z1 and Z2 or Z1 and R.
    Public Function C_Complex(X As Double):Complex
    Converts a real number into equal complex number.
    Public Function C_Opposite(Z As Complex):Complex
    Returns -Z.
    Public Function AbsComplex(Z As Complex):Double
    Returns the modulus of complex number z. Modulus calculation is performed using so called "safe" algorithm, that could never cause overflow when calculating intermediate results.
    Public Function Conj(Z As Complex):Complex
    Returns complex conjugate to z.
    Public Function CSqr(Z As Complex):Complex
    Returns the square of z.

    ALGLIB reference manual

    Packages and units


    DataAnalysis package
    dforest Decision forest classifier (regression model)
    kmeans K-means++ clustering
    lda Linear discriminant analysis
    linreg Linear models
    logit Logit models
    mlpbase Basic neural network operations
    mlpe Neural network ensemble models
    mlptrain Neural network training
    pca Principal component analysis
     
    DiffEquations package
    odesolver Ordinary differential equation solver
     
    FastTransforms package
    conv Fast real/complex convolution
    corr Fast real/complex cross-correlation
    fft Real/complex FFT
    fht Real Fast Hartley Transform
     
    Integration package
    autogk Adaptive 1-dimensional integration
    gkq Gauss-Kronrod quadrature generator
    gq Gaussian quadrature generator
     
    Interpolation package
    idwint Inverse distance weighting: interpolation/fitting
    lsfit Linear and nonlinear least-squares solvers
    polint Polynomial interpolation/fitting
    pspline Parametric spline interpolation
    ratint Rational interpolation/fitting
    spline1d 1D spline interpolation/fitting
    spline2d 2D spline interpolation
     
    LinAlg package
    ablas Level 2 and Level 3 BLAS operations
    bdsvd Bidiagonal SVD
    evd Eigensolvers
    inverseupdate Sherman-Morrison update of the inverse matrix
    ldlt LDLT decomposition
    matdet Determinant calculation
    matgen Random matrix generation
    matinv Matrix inverse
    ortfac Real/complex QR, LQ, bi(tri)diagonal, Hessenberg decompositions
    rcond Condition number estimate
    schur Schur decomposition
    sdet Determinant of a symmetric matrix
    sinverse Symmetric inversion
    spdgevd Generalized symmetric eigensolver
    srcond Condition number estimate for symmetric matrices
    svd Singular value decomposition
    trfac LU and Cholesky decompositions
     
    Optimization package
    minasa ASA bound constrained optimizer
    mincg Conjugate gradient optimizer
    minlbfgs Limited memory BFGS optimizer
    minlm Improved Levenberg-Marquardt optimizer
     
    Other package
    nearestneighbor Nearest neighbor search: approximate and exact
     
    Solvers package
    densesolver Dense linear system solver
    ssolve Symmetric dense linear system solver
     
    SpecialFunctions package
    airyf Airy functions
    bessel Bessel functions
    betaf Beta function
    chebyshev Chebyshev polynomials
    dawson Dawson integral
    elliptic Elliptic integrals
    expintegrals Exponential integrals
    fresnel Fresnel integrals
    gammafunc Gamma function
    hermite Hermite polynomials
    ibetaf Incomplete beta function
    igammaf Incomplete gamma function
    jacobianelliptic Jacobian elliptic functions
    laguerre Laguerre polynomials
    legendre Legendre polynomials
    psif Psi function
    trigintegrals Trigonometric integrals
     
    Statistics package
    binomialdistr Binomial distribution
    chisquaredistr Chi-Square distribution
    correlation Pearson/Spearman correlation coefficients
    correlationtests Hypothesis testing: correlation tests
    descriptivestatistics Descriptive statistics: mean, variance, etc.
    fdistr F-distribution
    hqrnd High quality random numbers generator
    jarquebera Hypothesis testing: Jarque-Bera test
    mannwhitneyu Hypothesis testing: Mann-Whitney-U test
    normaldistr Normal distribution
    poissondistr Poisson distribution
    stest Hypothesis testing: sign test
    studenttdistr Student's t-distribution
    studentttests Hypothesis testing: Student's t-test
    variancetests Hypothesis testing: F-test and one-sample variance test
    wsr Hypothesis testing: Wilcoxon signed rank test



    Sources:
    1. https://www.alglib.net/
    2. https://sites.google.com/site/chandanprogrammingdocs/platforms-frameworks/alglib
    3. https://newtonexcelbach.com/2010/05/20/installing-alglib-with-excel-vba/


    Here you can download GPL-licensed version of ALGLIB. Commercial users may use GPL-licensed code as unlimited trial version. But if you want to distribute something that includes GPL-ed code, you have to either distribute it under GPL too or buy commercial license.
    3.x branch
    Change Log
    alglib-3.1.0.cpp        zip tgz        C++ version
    alglib-3.1.0.csharp        zip tgz        C# version (100% managed code)
     
    pre-3.x releases
    Pre-3.x releases are not compatible with 3.x branch;
    however, they will be there for languages which were not ported to 3.x yet
    alglib-2.6.0.mpfr.zip Multiple precision version (MPFR)
    alglib-2.6.0.freepascal.zip FreePascal version
    alglib-2.6.0.delphi.zip Delphi version
    alglib-2.6.0.vb6.zip VBA version