I have the need to write a DLL but this is my first time (there's always one) and I have found a solution reading the documentaion. I ended up with this code:
library DLLFrazioni;
uses
System.SysUtils,
System.Classes,
Fractions in 'Fractions.pas';
{$R *.res}
function getFraction(a: integer; b: integer): PChar; stdcall; overload;
var f: TFraction;
begin
f := TFraction.Create(a, b);
try
Result := PChar(f.getFraction);
except
Result := PChar('NaN');
end;
end;
function getFraction(a: PChar): PChar; stdcall; overload;
var f: TFraction;
begin
f := TFraction.Create(a);
try
Result := PChar(f.getFraction);
except
Result := PChar('NaN');
end;
end;
exports
getFraction(a: integer; b: integer),
getFraction(a: Pchar);
begin
end.
There is a class called TFraction in Fraction.pas and it has this implementation (if needed):
type
TFraction = class
private
number: double;
num, den: integer;
fraction: string;
function hcf(x: integer; y: integer): integer;
public
//input num+den -> result is a fraction num/den
constructor Create(numerator: integer; denominator: integer); overload;
//input string 'num/den' -> result is a reduced num/den
constructor Create(value: PChar); overload;
function getFraction: string;
end;
Everything here is pretty easy.
I have to be able to load this dll with Delphi and C++ (Visual Studio) but I have a doubt that I haven't solved with google. As you can see I have declared another unit that contains the class so I can have the two things separated.
I am using stdcall as usual in delphi DLLs. I have the following questions:
- I have to create an object (
f: TFraction) because I need to get the return result fromgetFraction. Do I have to surround it with the usual try-finally statement? I thought that a try-except fits better because I want to avoid exceptions at runtime. - If I removed the try-except of course an exception can occur. In this case when I will call the function from my Delphi/C++ program I can handle it. But is that safe? Can I allow that a dll raises an exception?