我有一个C DLL,我正在编写一个C#interop类。
在C DLL中,其中一个关键方法填充了2d结构;结构由辅助方法分配和释放,如下所示:
// 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);
简单地编组My2dArray.arr
作为指针的指针看起来像一个问题。 我有什么方法可以为C#编组,这样我不需要C#代码不安全吗?
(我强烈希望尽可能避免修改我的C API,或至少保持最小化,但如果这是唯一的方法,这是一个选项。)
这是我目前使用的不安全的C#代码(从真实内容略微简化)。它工作正常,做我想要的,但需要不安全的使用:
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;
}
}
答案 0 :(得分:2)
我使用最新的编译器(C#7.0)(nuget)加上一个不安全的库(nuget)。
这里的要点是我不想通过复制Unmanaged2d
结构来编组,也不想复制数组。我想使用它们&#34;到位&#34;。我会在询问时使用ref return
加上一些Unsafe.As*
方法来读取单个MyPodStruct
,并使用二维索引器来隐藏所有内容。遗憾的是,Unsafe.As*
需要unsafe
关键字,因为其方法接受void*
而非接受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})"))));
}
作为旁注,似乎使用IntPtr
来使&#34;不安全&#34;代码&#34;安全&#34;越来越不满意了。例如,请参阅here,其中Span<T>(void*)
的重载请求接受Span<T>(IntPtr)
并已关闭,因为:
我们希望使用指针进行操作是使用指针进行显式操作,而不是将它们隐藏在IntPtr后面,这往往会给人一种虚假的安全感。
和here。
一般来说,您可以使用Marshal.ReadIntPtr
加BitConverter.Int64BitsToDouble(Marshal.ReadInt64(...))
来完成您的工作,例如:
[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;
}
}
此代码在技术上并不包含unsafe
的任何内容,但它与您的代码一样不安全。
啊......在C#中,你在C中所拥有的被称为锯齿状数组。它是一个数组数组(第一级指针数组指向许多二级元素数组)。它不是一个多维数组。