views:

139

answers:

2

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

A: 

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.

silent
As far as I know there are refcounted types in there, allocated via the Delphi heapmanager. The Olevariant way might avoid this.
Marco van de Voort
+6  A: 

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);
}
Robert Giesecke
+1. Basically, sticking to the data types and conventions one sees in type library import units seems like a good idea.
mghie
Hmmm... Nice. I'll give it a try tonight.
Fabricio Araujo