【发布时间】:2017-09-18 23:54:39
【问题描述】:
我需要编写一个 DLL,但这是我第一次(总是有一个),我找到了阅读文档的解决方案。我最终得到了这段代码:
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.
在 Fraction.pas 中有一个名为 TFraction 的类,它有这个实现(如果需要):
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;
这里的一切都很简单。
我必须能够用 Delphi 和 C++ (Visual Studio) 加载这个 dll,但我怀疑我没有用 google 解决。如您所见,我已经声明了另一个包含该类的单元,因此我可以将两者分开。
我在 delphi DLL 中像往常一样使用 stdcall。我有以下问题:
- 我必须创建一个对象(
f: TFraction),因为我需要从getFraction获取返回结果。我必须用通常的 try-finally 语句来包围它吗?我认为 try-except 更适合,因为我想在运行时避免异常。 - 如果我删除了 try-except 当然会发生异常。在这种情况下,当我从我的 Delphi/C++ 程序中调用该函数时,我可以处理它。但这安全吗?我可以允许 dll 引发异常吗?
【问题讨论】: