简体   繁体   中英

Marshalling array of struct (that contains an array of struct) from C# to Delphi (managed to unmanaged)

The C# struct:

public struct Table
{
    [MarshalAs(UnmanagedType.LPArray)]
    public Parameters[] parameters;
    public string Name;
    etc...
}

public struct Parameters
{
    public string parameterName;
    public string parametervalue;
}

I don't know the length of the 'Parameters[] parameters' array at design time.

So I could have:

Table[] tables = new Table[RandomNumber];

for (int i = 0; i < RandomNumber; i++)
{
    for (int j=0; j<AnotherRandomNumber; j++)
    {
        tables[i].parameters[j] = new Parameters() { parameterName = "", parametervalue = "" };
    }
}

Now I want to pass the tables array back to unmanaged code (Delphi)

The interface looks like this:

int GetTables([Out, MarshalAs(UnmanagedType.LPArray)] out Table[] results);

And the method in C#:

public int GetTables(out ReportTable[] results)

But the Delphi code gives an error:

Cannot marshal field ... arrays fileds must be paired with ByValArray or SafeArray.

I've tried the various UnmanagedType.xxx combinations but get errors no matter what.

Any ideas?

Thanks W

I've managed to 'fix' my silly issues! I replaced this:

public struct Table
{
    [MarshalAs(UnmanagedType.LPArray)]
    public Parameters[] parameters;
    public string Name;
    etc...
}

with:

[MarshalAs(UnmanagedType.ByValArray)]

I was under the impression before that I had to pass the size of the stcurt array but that is not the case.

Thanks W

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM