Numerics 0.55 released

0

Numerics 0.55 is available for download

The main improvements are:

1) Explicit DLL load is supported by the function

function LoadNumerics(const Name: string = ''): TF_RESULT;

and this is now the recommended method to load the dll because it enables error handling:

if LoadNumerics() < 0 then
  raise Exception.Create('!!! - DLL load error');

if the LoadNumerics was not called the dll is loaded transparently when needed.

2) More BigInteger functions implemented:

2.1) Integer square root:

    class function Sqrt(A: BigInteger): BigInteger; static;

2.2) Euclid algorithm (aka Greatest Common Divisor) and Extended Euclid algorithm:

    class function GCD(A, B: BigInteger): BigInteger; static;
    class function EGCD(A, B: BigInteger; var X, Y: BigInteger): BigInteger; static;

2.3) Modular arithmetic:

    class function ModPow(const BaseValue, ExpValue, Modulo: BigInteger): BigInteger; static;
    class function ModInverse(A, Modulo: BigInteger): BigInteger; static;

Most of the above functions were written while I was doing the programming assignments of the Coursera Cryptography 1 course by prof. Dan Boneh. It was fun to use my own BigInteger implementation.

3) C++ support added. I used free CodeBlocks IDE to port the PiBench console application to C++.

Merry Christmas and Happy New Year!

Advertisements

Goodbye, TObject

7

I’m not using TObject in my Delphi code anymore. Sure I use the core classes like TStream derived from TObject but I don’t derive my own classes from TObject or descendant classes. I am using a different OOP paradigm instead.
It all started when I was looking for a simple-to-use and efficient BigInteger type in Delphi and the solution seems absolutely evident now when I am looking back at it:

type
  IBigNumber = interface
/*
  interface methods
*/
  end;

type
  BigInteger = record
  private
    FNumber: IBigNumber;
  public
/*
  public methods and overloaded operators
*/
  end;

The BigInteger type is an interface reference wrapped in the advanced record; SizeOf(BigInteger) = SizeOf(Pointer).

Let us generalize the above idea. Instead of

type
  TMyObject = class
/*
..
*/
  end;

we use the alternative:

type
  IMyObject = interface
/*
..
*/
  end;

  TMyObject = record
  private
    FMyObject: IMyObject;
  public
/*
..
*/
  end;

You can see that the alternative requires more code typing. What we obtain for more work?

  • IMyObject can be implemented in DLL and used with different programming languages;
  • We obtain automatic memory management based on reference counting;
  • Automatic memory management makes possible fluent coding;
  • We can overload operators in TMyObject;
  • We get rid of all TObject overhead.

You may ask what about inheritance and polymorphism (late binding)? These are moved from classes (TMyObject) to interfaces (IMyObject), and the move makes coding more elastic. We now have separate inheritance of interfaces and implementations, and interfaces are always polymorphic (late bound).
You can notice that interfaces in Delphi are implemented using classes derived from TInterfacedObject but as I posted before this is not necessary – interfaces can be implemented in a more compact and efficient way.

And this closes the ring; TObject is not needed.

Consuming Delphi interfaces in Dephi and C++

5

An object-oriented DLL written in Delphi exports functions with parameters of interface type. A code consuming such DLL can use an interface reference directly, but a better way is to write a wrapper type which encapsulates an interface reference. Let us consider as an example a simple interface IBytes designed to work with byte arrays:

unit ITypes;

interface

type
  IBytes = interface
    function GetLength: Integer; stdcall;
    procedure Append(B: Byte); stdcall;
    procedure CopyTo(var C: IBytes); stdcall;
  end;

implementation

end.

The IBytes interface is implemented by the TByteObject class:

unit ByteObjects;

interface

uses ITypes;

type
  TByteObject = class(TInterfacedObject, IBytes)
    FBytes: array of Byte;
    function GetLength: Integer; stdcall;
    procedure Append(B: Byte); stdcall;
    procedure CopyTo(var C: IBytes); stdcall;
  end;

implementation

{ TByteObject }

procedure TByteObject.Append(B: Byte);
begin
  SetLength(FBytes, Length(FBytes) + 1);
  FBytes[Length(FBytes)]:= B;
end;

procedure TByteObject.CopyTo(var C: IBytes);
var
  Instance: TByteObject;

begin
  Instance:= TByteObject.Create;
  SetLength(Instance.FBytes, Length(FBytes));
  Move(Pointer(FBytes)^, Pointer(Instance.FBytes)^, Length(FBytes));
  C:= Instance;
end;

function TByteObject.GetLength: Integer;
begin
  Result:= Length(FBytes);
end;

end.

We implement the IBytes interface in DLL:

library TestDLL;

uses
  SysUtils,
  Classes,
  ITypes in 'ITypes.pas',
  ByteObjects in 'ByteObjects.pas';

procedure GetInterface(var I: IBytes); stdcall;
begin
  I:= TByteObject.Create;
end;

exports
  GetInterface;

{$R *.res}

begin
end.

The DLL exports the single function which creates instances of TByteObject class.

To consume the IBytes interface in Delphi we use an advanced record type to avoid the unnecessary overhead of Delphi classes:

unit ByteWrappers;

interface

uses Windows, ITypes;

type
  TGetInterface = procedure(var I: IBytes); stdcall;

var
  GetInterface: TGetInterface;

function LoadDll(const Name: string): Boolean;

type
  TMyBytes = record
  private
    FBytes: IBytes;
  public
    procedure Append(B: Byte);
    procedure CopyTo(var C: TMyBytes);
    function GetLength: Integer;
    procedure Free;
  end;

implementation

{ TMyBytes }

procedure TMyBytes.Append(B: Byte);
begin
  if (FBytes = nil) then GetInterface(FBytes);
  FBytes.Append(B);
end;

procedure TMyBytes.CopyTo(var C: TMyBytes);
begin
  if (FBytes = nil) then C.FBytes:= nil
  else FBytes.CopyTo(C.FBytes);
end;

procedure TMyBytes.Free;
begin
  FBytes:= nil;
end;

function TMyBytes.GetLength: Integer;
begin
  if (FBytes = nil) then Result:= 0
  else Result:= FBytes.GetLength;
end;

function LoadDll(const Name: string): Boolean;
var
  LibHandle: THandle;

begin
  LibHandle:= LoadLibrary(PChar(Name));
  if (LibHandle <> 0) then begin
    @GetInterface:= GetProcAddress(LibHandle, 'GetInterface');
    if @GetInterface <> nil then begin
      Result:= True;
      Exit;
    end;
    FreeLibrary(LibHandle);
  end;
  Result:= False;
end;

end.

And simple test application to be sure everything works as expected:

program Test;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ITypes in 'ITypes.pas',
  ByteWrappers in 'ByteWrappers.pas';

procedure TestInterface;
var
  Bytes1, Bytes2: TMyBytes;

begin
  Bytes1.Append(0);
  Bytes1.CopyTo(Bytes2);
  Bytes1.Append(0);
  Writeln(Bytes1.GetLength, ' -- ', Bytes2.GetLength);
end;

begin
  try
    ReportMemoryLeaksOnShutdown:= True;
    if LoadDll('TestDLL.dll')
      then TestInterface
      else Writeln('Can''t load TestDLL.dll');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

So far so good; now we want to consume the above Delphi interface in a C++ structure (or a class – there is no difference between a C++ structure and a C++ class here). The solution is:

// ByteWrappers.hpp
#ifndef BYTEWRAPPERS_H_INCLUDED
#define BYTEWRAPPERS_H_INCLUDED

#include <string>

using namespace std;

typedef uint8_t Byte;
typedef int32_t Integer;

bool LoadDll(string Name);

class IBytes {
  public:
    virtual Integer __stdcall QueryInterface(void* riid, void** ppvObject) = 0;
    virtual Integer __stdcall AddRef() = 0;
    virtual Integer __stdcall Release() = 0;
    virtual Integer __stdcall GetLength() = 0;
    virtual void __stdcall Append(Byte B) = 0;
    virtual void __stdcall CopyTo(IBytes** C) = 0;
};

class MyBytes {
  private:
    IBytes* FBytes;
  public:
    MyBytes() : FBytes(NULL) {};    // default constructor
    MyBytes(const MyBytes& A)       // copy constructor
    {
    	FBytes = A.FBytes;
    	if (FBytes != NULL)
    	{
    		FBytes->AddRef();
    	}
    };

    ~MyBytes()                      // destructor
    {
  	    if (FBytes != NULL)
  	    {
  		    FBytes->Release();
  		    FBytes = NULL;
  	    }
    };

    MyBytes& operator= (const MyBytes& A)   // assignment
    {
        if (A.FBytes != NULL)
            A.FBytes->AddRef();
        if (FBytes != NULL)
            FBytes->Release();
        FBytes = A.FBytes;
        return *this;
    }

    void Free()
    {
        if (FBytes != NULL)
        {
            FBytes->Release();
            FBytes = NULL;
        }
    }

    void Append(Byte B);
    void CopyTo(MyBytes& C);
    Integer GetLength();
};

#endif // BYTEWRAPPERS_H_INCLUDED
// ByteWrappers.cpp
#include <windows.h>
#include "ByteWrappers.hpp"

typedef void(__stdcall *PGetInterface)(IBytes**);
PGetInterface GetInterface = 0;

void MyBytes::Append(Byte B)
{
    if (FBytes == NULL) GetInterface(&FBytes);
    FBytes->Append(B);
}

void MyBytes::CopyTo(MyBytes& C)
{
    if (FBytes == NULL) C.Free();
    else FBytes->CopyTo(&C.FBytes);
}

Integer MyBytes::GetLength()
{
    if (FBytes == NULL) return 0;
    else return FBytes->GetLength();
}

bool LoadDll(string Name)
{
    HINSTANCE LibHandle;

    LibHandle = LoadLibrary(Name.c_str());
    if (LibHandle != 0)
    {
        GetInterface = (PGetInterface)GetProcAddress(LibHandle, "GetInterface");
        if (GetInterface != NULL) return true;
        FreeLibrary(LibHandle);
    }
    return false;
}

Test application:

#include <iostream>
#include <string>
#include "ByteWrappers.hpp"

using namespace std;

void TestInterface(){
    MyBytes Bytes1;
    MyBytes Bytes2;

    Bytes1.Append(0);
    Bytes1.CopyTo(Bytes2);
    Bytes1.Append(0);
    cout << Bytes1.GetLength() << " -- " << Bytes2.GetLength() << endl;
}

int main()
{
    if (LoadDll("TestDLL.dll"))
        TestInterface();
    else
        cout << "Can't load TestDLL.dll" << endl;
    return 0;
}

Some details worth being mentioned:

  • Delphi interfaces are always derived from IUnknown; a corresponding pure abstract C++ class should also define IUnknown methods;
  • Delphi interface type is kind of a pointer to the corresponding C++ abstract class, so sometimes we need one more level of indirection in C++ code;
  • Delphi interface variables are always initialized to nil by the compiler; in C++ we need default constructor to implement the nil-initialization;
  • Delphi interfaces are automatically released (i.e. call IUnknown._Release method) when an interface variable goes out of scope; In C++ we implement the same functionality in destructor;
  • Interface assignment in Delphi implicitly calls _Addref and _Release methods of IUnknown; in C++ we overload the assignment operator to implement the interface assignment correctly;
  • C++ supports variable initialization like this:
        MyBytes Bytes1;
        Bytes1.Append(0);
        MyBytes Bytes2 = Bytes1;
    

    to implement it correctly in our case we need a copy constructor.