PInvoke struct with nested struct array

276 views Asked by At

I'm trying to PInvoke a method which has a struct parameter with nested struct array pointer. The c declaration looks like this:

duckdb_state duckdb_query(duckdb_connection connection, const char *query, duckdb_result *out_result);

typedef struct {
    void *data;
    bool *nullmask;
    duckdb_type type;
    char *name;
} duckdb_column;

typedef struct {
    idx_t column_count;
    idx_t row_count;
    duckdb_column *columns;
    char *error_message;
} duckdb_result;

I declared them in C# like this:

[DllImport("duckdb.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "duckdb_query")]
public static extern DuckdbState DuckdbQuery(IntPtr connection, string query, out DuckdbResult result);

    [StructLayout(LayoutKind.Sequential)]
    public struct DuckdbColumn
    {
        IntPtr data;
        bool nullmask;  
        DuckdbType type;
        string name;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct DuckdbResult
    {
        public long column_count;
        public long row_count;

        public IntPtr columns;
        public string error_message;
    }

But when I try to execute the query and read the columns I don't get any meaningful data:

result = DuckdbQuery(connection, "SELECT * FROM integers", out queryResult);

DuckdbColumn[] columns = new DuckdbColumn[queryResult.column_count];
var queryResultColumns = queryResult.columns;
            
var columnPointer = Marshal.ReadIntPtr(queryResultColumns);
var ptrToStructure = (DuckdbColumn)Marshal.PtrToStructure(columnPointer, typeof(DuckdbColumn));

column data

How should I change the PInvoke declarations so that I can read the columns after executign the query?

There is example c code at: DuckDB c example

Update 1

I can get column names with the following code:

for (int i = 0; i < queryResult.column_count; i++)
{
    var column = (DuckdbColumn)Marshal.PtrToStructure(queryResult.columns + 8 + (Marshal.SizeOf<DuckdbColumn>() + 8) * i, typeof(DuckdbColumn));
    columns[i] = column;
}

but type field still says DUCKDB_TYPE_INVALID

enter image description here enter image description here

Update 2

As suggested by David in his answer I changed bool nullmask;to IntPtr nullmask; and I can now read column information like this:

for (int i = 0; i < queryResult.column_count; i++)
{
    var column = (DuckdbColumn)Marshal.PtrToStructure(queryResult.columns + Marshal.SizeOf<DuckdbColumn>() * i, typeof(DuckdbColumn));
    columns[i] = column;
}
1

There are 1 answers

3
David Heffernan On BEST ANSWER

You have translated this field incorrectly

bool *nullmask

This is not a bool it's a pointer. Declare it as

IntPtr nullmask;

There could be other errors because we can't see all the translations. Additionally, the +8 in your array access pointer arithmetic looks suspicious.