C# 有没有一种简单的方法可以将包含指针数组的数据结构从非托管整理到托管
好的,我一直在尝试整理一个数据结构,它在C/C++格式中有这样的等价物:C# 有没有一种简单的方法可以将包含指针数组的数据结构从非托管整理到托管,c#,arrays,pointers,struct,marshalling,C#,Arrays,Pointers,Struct,Marshalling,好的,我一直在尝试整理一个数据结构,它在C/C++格式中有这样的等价物: Struct ResultsRecord { int LengthOutMD; // this contains the size for the arrays below. float *OutMD; float *OutAxialLoad; float *OutNormalForce } 这是dll文件中非托管代码中包含的函数: typedef int (cdecl *
Struct ResultsRecord
{
int LengthOutMD; // this contains the size for the arrays below.
float *OutMD;
float *OutAxialLoad;
float *OutNormalForce
}
这是dll文件中非托管代码中包含的函数:
typedef int (cdecl *ReadResultsTnDAnalysis) (wchar_t* ResultFileName, struct ResultsRecord* TnDResultsRecord);
现在,我的解决方案暂时不起作用:因为我找不到一种简单的方法来整理指向数组初始值的指针:数组的大小是先验未知的
public class APIforEngine
{
[DllImport("TnDAnalysisDLL.dll", EntryPoint = "ReadResultsTnDAnalysis", CallingConvention = CallingConvention.Cdecl
public static extern int ReadResultsTnDAnalysis(string resultFileName,
ref TnDResultsRecord tnDResultsRecord);, CharSet = CharSet.Auto)]
}
[StructLayout(LayoutKind.Sequential), Serializable]
public struct TnDResultsRecord
{
public int LengthOutMD;
[MarshalAs(UnmanagedType.LPArray)]
public float[] OutMD;
[MarshalAs(UnmanagedType.LPArray)]
public float[] OutAxialLoad;
[MarshalAs(UnmanagedType.LPArray)]
public float[] OutNormalForce;
}
非常感谢你的帮助
现在我正在考虑在一个中间C++项目中使用DLL,把数据转换成C语言容易读取的东西,并把它用在我的C语言解决方案中。即使是这条路线,我也要看看它是否真的可行,因为对于一个人来说,我不知道如何使用它。在本地C++中还是使用CLR?如果我使用CLR,我是使用InterOpServices命名空间类还是使用头文件使用它。相关:你无法说服pinvoke marshaller为你这样做,也无法告诉它数组的长度。只需自己动手,将数组成员声明为IntPtr。并在函数调用后使用Marshal.Copy()复制数组。请注意内存管理问题,在这种情况下,谁应该为阵列释放内存是非常不清楚的。你不能。但对于“结果”记录,您通常必须这样做。也许你应该为数组预先分配内存,你可以用Marshal.AllocHGlobal()来完成。谢谢!这解决了我的问题。