[英]How to cast an array of structures (of double values) to an array of double values
我正在嘗試創建一個包裝,將System.Numeric.Complex數組視為double數組,即將{{1,2},{3,4},{5,6},{7,8}
視為{1,2,3,4,5,6,7,8}
。 我將這些數組用於FFT,因此這種方式將更加高效,因為避免了復制和迭代大數組。 但是我陷入了一個奇怪的嵌合怪獸:一個類型為double[] {System.Numerics.Complex[4]
Double數組對象,而不是double[8]
!!。 那是什么?
我不是互操作專家,所以請原諒任何重大錯誤; 我在這里和這里讀了一些相關的東西,我想知道情況是否是這些數組重疊了。 他的代碼幾乎可以工作,除了它返回一半的值:
//using System.Runtime.InteropServices;
//using System.Numeric;
[StructLayout(LayoutKind.Explicit)]
public struct ComplexArray2serialWrapper
{
[FieldOffset(0)] private Complex[] ComplexArray;
[FieldOffset(0)] private double[] DoubleArray;
public ComplexArray2serialWrapper(Complex[] NewcomplexArray) : this() { ComplexArray = NewcomplexArray; }
public ComplexArray2serialWrapper(double[] NewSerialComplexArray) : this() { DoubleArray = NewSerialComplexArray; }
public static implicit operator double[] (ComplexArray2serialWrapper source) { return source.DoubleArray; }
}
public static void TestWrapper()
{
Complex[] cc = { new Complex(1, 2), new Complex(3, 4), new Complex(5, 6), new Complex(7, 8) };
double[] DoubleComplexChimeraMonster = new ComplexArray2serialWrapper(cc);
var parenttype = DoubleComplexChimeraMonster.GetType(); // result = System.Numerics.Complex[]
//!!! but in watch window type shown as= double[] {System.Numerics.Complex[4]}
var ChildrenType = DoubleComplexChimeraMonster[0].GetType(); //System.Double
//In Watch window, children types shown chimeric:
//{ (1, 2)} Double {System.Numerics.Complex}
//{ (3, 4)} Double {System.Numerics.Complex}
//{ (5, 6)} Double {System.Numerics.Complex}
//{ (7, 8)} Double {System.Numerics.Complex}
double i1 = DoubleComplexChimeraMonster[0]; //=1 (as expected)
double i2 = DoubleComplexChimeraMonster[1]; //=2 (as expected)
double i3 = DoubleComplexChimeraMonster[2]; //=3 (as expected)
double i4 = DoubleComplexChimeraMonster[3]; //=4 (as expected)
var l = DoubleComplexChimeraMonster.Length; //=4 (8 expected)
//So trying to get i5-i8 will throw an exception e.g.:
//DoubleComplexChimeraMonster(4) --> exception (5 expected)
}
您期望數組僅存儲雙精度型。 但是它們還存儲數組長度和對類型描述符的引用。 因此,重疊兩種.NET類型的方法不起作用。 C#不是C。
DoubleComplexChimeraMonster
的靜態類型為double[]
,但是GetType()
檢索運行時類型,碰巧是Complex[]
。
在相同的存儲位置重疊值適用於原始值類型。 但是System.Array
是一個類。
正如Marc Gravell在您提供的鏈接的答案中所說的那樣,不安全的指針可能是解決之道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.