Can I marshal a C-struct with a 2d array without using “unsafe”?

给你一囗甜甜゛ 提交于 2021-02-07 21:10:09

问题


I have a C DLL that I'm writing a C# interop class for.

In the C DLL, one of the key methods fills a 2d structure; the structure is allocated and freed by helper methods, like so:

// Simple Struct Definition -- Plain Old Data
typedef struct MyPodStruct_s
{
    double a;
    double b;
} MyPodStruct;

typedef struct My2dArray_s
{
    MyPodStruct** arr; // allocated by Init2d;
                       // array of arrays.
                       // usage: arr[i][j] for i<n,j<m
    int n;
    int m;
} My2dArray;

void Init2d(My2dArray* s, int n, int m);
void Free2d(My2dArray* s);

// fill according to additional work elsewhere in the code:
void Fill2dResult(My2dArray* result);

Simply marshaling My2dArray.arr as a pointer to a pointer looks like an issue. Is there any way I can marshal this for C#, so that I don't need the C# code to be unsafe?
(I'd strongly prefer to avoid modifying my C API if possible, or at least keeping the changes minimal, but this is an option if it's the only way.)

Here's the unsafe C# code I have presently (simplified slightly from the real thing). It works fine and does what I want, but requires unsafe usage:

class FooInterop
{
    public struct MyPodStruct // Plain Old Data
    {
        public double a;
        public double b;
    };

    [StructLayout(LayoutKind.Sequential)]
    private unsafe struct unmanaged2d
    {
        public MyPodStruct** arr;
        public int n;
        public int m;
    };

    [DllImport("Foo.DLL", EntryPoint = "Init2d", CallingConvention = CallingConvention.Cdecl)]
    private static extern void unsafe_Init2d(ref FooInterop.unmanaged2d, int n, int m);
    [DllImport("Foo.DLL", EntryPoint = "Free2d", CallingConvention = CallingConvention.Cdecl)]
    private static extern void unsafe_Free2d(ref FooInterop.unmanaged2d);
    [DllImport("Foo.DLL", EntryPoint = "Fill2dResult", CallingConvention = CallingConvention.Cdecl)]
    private static extern void unsafe_Fill2dResult(ref FooInterop.unmanaged2d);

    public static FooInterop.MyPodStruct[,] Fill2dResult()
    {
        unmanaged2d unsafeRes = new unmanaged2d();
        FooInterop.MyPodStruct[,] res;

        unsafe_Init2d(ref unsafeRes, n, m); // I have n, m from elsewhere
        unsafe_Fill2dResult(ref unsafeRes );
        res = new FooInterop.MyPodStruct[n,m];

        for (int i=0; i<n; ++i)
        {
            for (int j=0; j<m; ++j)
            {
                unsafe
                {
                    res[i, j] = unsafeRes.arr[i][j];
                }
            }
        }

        unsafe_Free2d(ref unsafeRes );

        return res;
    }
}

回答1:


Mmmmh... I'll post some code, that probably you don't need :-)

I'm using the latest compiler (C# 7.0) (nuget) plus an unsafe library (nuget).

The point here is that I don't want to marshal by copy the Unmanaged2d struct, nor I want to copy the array. I want to use them "in place". I'll use the ref return plus some Unsafe.As* methods to read the single MyPodStruct when asked, and a bidimensional indexer to hide everything. sadly the Unsafe.As* require the unsafe keyword, because its methods accept void* instead of accepting IntPtr.

[StructLayout(LayoutKind.Sequential, Size = 16)]
public struct MyPodStruct // Plain Old Data
{
    public double a;
    public double b;
};

[StructLayout(LayoutKind.Sequential)]
public struct Unmanaged2d
{
    public IntPtr arr;
    public int n;
    public int m;

    public unsafe ref MyPodStruct this[int x, int y]
    {
        get
        {
            if (x < 0 || x >= n)
            {
                throw new ArgumentOutOfRangeException(nameof(x));
            }

            if (y < 0 || y >= m)
            {
                throw new ArgumentOutOfRangeException(nameof(y));
            }

            IntPtr ptr = Marshal.ReadIntPtr(arr, x * sizeof(IntPtr));
            IntPtr ptr2 = ptr + y * 16; // 16 == sizeof(MyPodStruct)
            return ref Unsafe.AsRef<MyPodStruct>(ptr2.ToPointer());
        }
    }
}

unsafe_Init2d(ref unsafeRes, n, m);

// We increase all the values of a and b, just to show that we can!
for (int i = 0; i < u.n; i++)
{
    for (int j = 0; j < u.m; j++)
    {
        u[i, j].a += 10;
        u[i, j].b++;
    }
}

// We print them
for (int i = 0; i < u.n; i++)
{
    Console.WriteLine(string.Join(";", Enumerable.Range(0, u.m).Select(x => string.Format($"({u[i, x].a},{u[i, x].b})"))));
}

As a sidenote, it seems that using IntPtr to make "unsafe" code "safe" is getting frowned upon. See for example here where a request for an overload to Span<T>(void*) that accept a Span<T>(IntPtr) and has been closed because:

We want operations with pointers to be explicit operation with pointers, and not hide them behind IntPtr that tend to give people a false sense of safety.

and here.

In general what you want to do can be done with some Marshal.ReadIntPtr plus BitConverter.Int64BitsToDouble(Marshal.ReadInt64(...)), like:

[StructLayout(LayoutKind.Sequential)]
public struct Unmanaged2d
{
    public IntPtr arr;
    public int n;
    public int m;

    public static MyPodStruct[,] Fill2dResult()
    {
        Unmanaged2d unsafeRes = new Unmanaged2d();

        //unsafe_Init2d(ref unsafeRes, n, m); // I have n, m from elsewhere
        //unsafe_Fill2dResult(ref unsafeRes);

        MyPodStruct[,] res = new MyPodStruct[unsafeRes.n, unsafeRes.m];

        for (int i = 0; i < unsafeRes.n; i++)
        {
            IntPtr row = Marshal.ReadIntPtr(unsafeRes.arr, i * IntPtr.Size);

            for (int j = 0, offset = 0; j < unsafeRes.m; j++)
            {
                // Automatic marshaling of MyPodStruct
                // res[i, j] = Marshal.PtrToStructure<MyPodStruct>(row + j * (sizeof(double) + sizeof(double)));

                // Manual marshaling

                // a
                long temp1 = Marshal.ReadInt64(row, offset);
                double dbl1 = BitConverter.Int64BitsToDouble(temp1);
                offset += sizeof(double);

                // b
                long temp2 = Marshal.ReadInt64(row, offset);
                double dbl2 = BitConverter.Int64BitsToDouble(temp2);
                offset += sizeof(double);

                res[i, j] = new MyPodStruct { a = dbl1, b = dbl2 };
            }
        }

        //unsafe_Free2d(ref unsafeRes);

        return res;
    }
}

This code doesn't technically contain anything that is unsafe, but it is as much unsafe as your code.

Ah... and in C#, what you have in C is called a jagged array. It is an array of arrays (a first level of arrays of pointers that point to many second level arrays of elements). It isn't a multidimensional array.



来源:https://stackoverflow.com/questions/50610552/can-i-marshal-a-c-struct-with-a-2d-array-without-using-unsafe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!