How do I (or if I can't) use Variants on simple DLLs?
I want to expose some functionality of a internal object as a DLL - but that functionality uses variants. But I need to know: I can export a function with Variant parameters and/or return - or is better to go to an string-only re开发者_StackOverflowpresentation?
What is better, from language-agnostic POV (the consumer is not made with Delphi - but all will run in Windows)?
You could use OleVariant, which is the variant value type that is used by COM. Make sure not to return it as a function result as stdcall and complex result types can easily lead to problems.
A simple example library DelphiLib;
uses
SysUtils,
DateUtils,
Variants;
procedure GetVariant(aValueKind : Integer; out aValue : OleVariant); stdcall; export;
var
doubleValue : Double;
begin
case aValueKind of
1: aValue := 12345;
2:
begin
doubleValue := 13984.2222222222;
aValue := doubleValue;
end;
3: aValue := EncodeDateTime(2009, 11, 3, 15, 30, 21, 40);
4: aValue := WideString('Hello');
else
aValue := Null();
end;
end;
exports
GetVariant;
How it could be consumed from C#:
public enum ValueKind : int
{
Null = 0,
Int32 = 1,
Double = 2,
DateTime = 3,
String = 4
}
[DllImport("YourDelphiLib",
EntryPoint = "GetVariant")]
static extern void GetDelphiVariant(ValueKind valueKind, out Object value);
static void Main()
{
Object delphiInt, delphiDouble, delphiDate, delphiString;
GetDelphiVariant(ValueKind.Int32, out delphiInt);
GetDelphiVariant(ValueKind.Double, out delphiDouble);
GetDelphiVariant(ValueKind.DateTime, out delphiDate);
GetDelphiVariant(ValueKind.String, out delphiString);
}
As far as I know there is no problems to work with Variant variable type in other languages. But it will be great if you export the same functions for different variable types.
精彩评论