问题描述
我有一个C DLL,我正在为其编写C#互操作类.
I have a C DLL that I'm writing a C# interop class for.
在C DLL中,关键方法之一是填充2d结构.该结构是通过辅助方法分配和释放的,如下所示:
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);
简单地封送 My2dArray.arr
作为指向指针的指针看起来像一个问题.有什么办法可以将其编组为C#,以便我 不需要C#代码不安全吗?
(我强烈希望避免在可能的情况下修改我的C API,或者至少将更改保持在最小限度,但这是唯一的选择.)
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.)
这是我目前使用的不安全的C#代码(与实际情况略有简化).它可以正常工作并满足我的要求,但需要使用不安全的方法:
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;
}
}
推荐答案
Mmmmmh ...我将发布一些代码,可能您不需要:-)
Mmmmh... I'll post some code, that probably you don't need :-)
我正在使用最新的编译器(C#7.0)( nuget )以及不安全的库( nuget ).
I'm using the latest compiler (C# 7.0) (nuget) plus an unsafe library (nuget).
这里的要点是,我不想通过复制 Unmanaged2d
结构进行封送,也不想复制该数组.我想就地"使用它们.我将使用 ref return
以及一些 Unsafe.As *
方法来读取单个 MyPodStruct
,并使用一个二维索引器来隐藏所有内容.遗憾的是, Unsafe.As *
需要 unsafe
关键字,因为其方法接受 void *
而不是接受 IntPtr
.
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})"))));
}
作为一个旁注,似乎不习惯使用 IntPtr
来使不安全"代码安全".参见例如此处,其中请求对进行重载Span< T>(void *)
接受 Span< T>(IntPtr)
,并且由于以下原因而被关闭:
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:
和此处.
通常,您可以使用某些 Marshal.ReadIntPtr
加上 BitConverter.Int64BitsToDouble(Marshal.ReadInt64(...))
来完成操作,例如:
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.
啊...在C#中,您在C中所拥有的称为锯齿状数组.它是一个数组数组(指向许多第二级元素数组的指针的第一级数组).它不是多维数组.
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.
这篇关于我可以在不使用“不安全"的情况下封送带有2d数组的C结构吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!