Question

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 representation?

What is better, from language-agnostic POV (the consumer is not made with Delphi - but all will run in Windows)?

Was it helpful?

Solution

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);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top