我有一个 C DLL,我正在为其编写 C# 互操作类。
在C DLL中,其中一个关键方法填充了一个二维结构;该结构由辅助方法分配和释放,如下所示:
// 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
编码(marshal)为指向指针的指针看起来像是一个问题。 有什么方法可以为 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;
}
}
最佳答案
嗯...我会发布一些代码,您可能不需要 :-)
我使用的是最新的编译器 (C# 7.0) ( nuget ) 加上一个不安全的库 ( nuget )。
这里的重点是我不想通过复制 Unmanaged2d
来编码struct,我也不想复制数组。我想“就地”使用它们。我将使用 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
使“不安全”的代码变得“安全”是不受欢迎的。参见示例 here重载请求 Span<T>(void*)
接受 Span<T>(IntPtr)
并且已经关闭,因为:
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.
和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 中拥有的称为交错数组。它是一个数组数组(指向许多第二级元素数组的第一级指针数组)。它不是多维数组。
关于c# - 我可以在不使用 "unsafe"的情况下使用二维数组编码 C 结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610552/