当前位置: 首页 > 编程语言 > C#

MarshalCStructContainingVariableLengthArray分享

时间:2023-04-11 12:13:29 C#

MarshalCStructContainingVariableLengthArray无法获得比指向结构表示的指针和浮点指针更好的结果。非托管表示:typedeffloatsmpl_t;typedefstruct{uint_t长度;/**<缓冲区的长度*/smpl_t*data;/**<长度的数据向量::fvec_t.length*/}fvec_t;托管表示:[StructLayout(LayoutKind.Sequential)]publicunsafestructfvec_t1{publicuintlength;公共浮动*数据;}[DllImport("libaubio-4.dll",EntryPoint="new_fvec",PreserveSig=true,CharSet=CharSet.Ansi,CallingConvention=CallingConvention.Cdecl)]publicstaticexternunsafefvec_t1*new_fvec1(uintlength);我想要的是一个.NET样式数组,其中数据为float[],但如果我确实将结构更改为下面的形式,我将无法在上面的外部函数中获取地址、获取大小或声明指向托管类型的指针。[StructLayout(LayoutKind.Sequential)]publicunsafestructfvec_t1{publicuintlength;公共浮动[]数据;显然不可能按原样编组可变长度数组,这是正确的还是还有办法实现这个目标?简短的回答你不能将可变长度数组编组为数组,因为大小未知,互操作编组服务不能编组数组元素,但如果你知道大小,它将看起来像这样:intarr[15]你会能够像这样编组它:[MarshalAs(UnmanagedType.LPArray,SizeConst=15)]int[]arr如果你不知道你想要的数组的长度,你可以将它转换为intprt并处理inptr但首先你需要创建2个结构[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]structfvec_t1{publicuintwhatever;公共int[]数据;}另一个如下:[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)]structfvec_t2{publicuintwhatever;}创建一个函数来初始化数组,如下所示privatestaticint[]ReturnIntArray(){int[]myInt=newint[30];for(inti=0;iinstance实例化第一个结构fvec_t1instance=newfvec_t1();instance.whatever=10;instance.data=ReturnIntArray();实例化第二个结构fvec_t2instance1=newfvec_t2();instance1.whatever=instance.whateverisdata数组的扩展空间动态分配fvec_t2结构体的空间IntPtrptr=Marshal.AllocHGlobal(Marshal.SizeOf(typeof(fvec_t2))+Instance.data.Length);将fvec_t2已有的字段值转移到ptr指向的内存空间Marshal.StructureToPtr(instance1,ptr,true);计算应该位于fvec_t2结构体末尾的数据数组字段的偏移量intoffset=Marshal.SizeOf(typeof(fvec_t2));根据偏移量获取数据数组字段的内存地址IntPtraddress=newIntPtr(ptr.ToInt32()+offset);将数据复制到ptrMarshal.Copy(instance.data,0,address,instance.data.Length);调用boolsuccess=dllfunction(ptr);元帅.FreeHGlobal(ptr);ptr=IntPtr.Zero;在上面的例子中,我肯定会使用SizeParamIndex。[StructLayout(LayoutKind.Sequential)]publicstructfvec_t1{uintlength;[MarshalAs(UnmanagedType.LPArray,SizeParamIndex=0)]float[]数据;}祝你好运。以上就是C#学习教程:Marshal包含了变长数组的C结构共享的所有内容。如果对大家有用,需要了解更多C#学习教程,希望大家多多关注---本文来自网络收集,不代表任何内容,如涉及侵权,请点击右转联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢