1

I'm using UnmanagedExports to call .NET C# class library functions from a Delphi Win32 Program. Works like a charme!

What I have not yet discovered is how to declare array types (like int[] or IMyUnknownBasedInterface[]) on the C# and on the Delphi side, so that I could exchange arrays between the two languages. If not possible, I'd also be happy to use some kind of a collection object or indexer methods.

Any ideas?

2 Answers 2

2

On the C# side do it like this:

[DllExport("Foo", CallingConvention = CallingConvention.Stdcall)]
static extern void Foo(int[] a, int len);

And on the Delphi side like this:

procedure Foo(a: PInteger; len: Integer); stdcall; external 'manageddll.dll';

To call the function from Delphi you would do like so:

var
  a: array of Integer;
....
SetLength(a, 666);
//populate a
Foo(PInteger(a), Length(a));
Sign up to request clarification or add additional context in comments.

2 Comments

Cool, thanks David. Does the same apply if I want to pass an array of interfaces (IMyUnknownBasedInterface[])? Thanks!
I believe so. On the C# IMyUnknownBasedInterface[] matches a pointer to the first element of the array. So on the Delphi side you want to pass PIMyUnknownBasedInterface where PIMyUnknownBasedInterface = ^IMyUnknownBasedInterface. Not sure how reference counting is handled on the C# side though.
0

This is easy on the C# side, but it can be a royal PITA on the Delphi side.

The Problem here is, that if you have an Array property of an Interface that got marshalled from native, then the CLR will be very picky about the Array size.

Your best shot is a safe Array, which is easily declared in C#...

public interface ISample
{
    int[] YourArray
    {
        [return:MarshalAs(UnmanagedType.SafeArray)]
        get;
    }

However, safe arrays are quite a pain to deal with on the Delphi side.

For my own stuff, I simply did not publish Arrays in the Interfaces that got shared between native and C#. I used an Interface that mimics IEnumerable, but can be easily implemented in Delphi or C#.

When you let it return another interface that provides the methods MoveNext, GetCurrent and a property Current, then both C# and Delphi let you happily foreach over it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.