using FxpConvert.Common; using System.Reflection; using System.Runtime.CompilerServices; namespace NIFPGA { public sealed class FPGAArrayFXPWriteProperty : FPGABaseProperty { Interop.NiFpgaDll_ReadArrayU8 Read; Interop.NiFpgaDll_WriteArrayU8 Write; private NiFpga_FxpTypeInfo _TypeInfo; private IFxpConvert _Convert; private ulong[] tempbuffer = new ulong[0]; private double[] doubles = new double[0]; private ulong[] tempvalue = new ulong[0]; internal FPGAArrayFXPWriteProperty(FPGASession session, uint indicator, uint count,NiFpga_FxpTypeInfo typeInfo, IFxpConvert convert) : base(session, indicator,false) { _Convert = convert; Count = count; doubles = new double[count]; tempvalue = new ulong[count]; _TypeInfo = typeInfo; tempbuffer = new ulong[(int)Math.Ceiling(typeInfo.wordLength * count / (Unsafe.SizeOf() * 8.0))]; Read = _Session.GetDelegate(); Write = _Session.GetDelegate(); } private double[] GetData() { _Session.CheckResult(Read(_Session.Session, Indicator, ref Unsafe.As(ref tempbuffer[0]), (uint)tempbuffer.Length*8)); int tempdatalen = Unsafe.SizeOf() * 8; ulong mask = (1ul << _TypeInfo.wordLength) - 1; for (int i = 0; i < Count; i++) { int index = i * _TypeInfo.wordLength / tempdatalen; int bitindex = tempdatalen - (i * _TypeInfo.wordLength % tempdatalen); if (bitindex >= _TypeInfo.wordLength) { tempvalue[i] = (tempbuffer[index] >> (bitindex - _TypeInfo.wordLength)) & mask; } else { tempvalue[i] = (((tempbuffer[index] & ((1ul << bitindex) - 1)) << (_TypeInfo.wordLength - bitindex)) | (tempbuffer[index + 1] >> (tempdatalen - (_TypeInfo.wordLength - bitindex)))); } } _Convert.FxpConvertToDouble(ref tempvalue[0], _TypeInfo, ref doubles[0], Count); return doubles; } private void SetData(double[] values) { if (values.Length != Count) return; _Convert.DoubleConvertToDxp(ref values[0], _TypeInfo, ref tempvalue[0], Count); int tempdatalen = Unsafe.SizeOf() * 8; for (int i = 0; i < Count; i++) { int index = i * _TypeInfo.wordLength / tempdatalen; int bitindex = tempdatalen - (i * _TypeInfo.wordLength % tempdatalen); var b =(tempvalue[i] & ((1ul << _TypeInfo.wordLength) - 1)); if (bitindex >= _TypeInfo.wordLength) { tempbuffer[index] |= (b << (bitindex - _TypeInfo.wordLength)); } else { tempbuffer[index] |= (b >> (_TypeInfo.wordLength - bitindex)); tempbuffer[index + 1] |= ((b & ((1ul << (_TypeInfo.wordLength - bitindex)) - 1)) << (tempdatalen - (_TypeInfo.wordLength - bitindex))); } } _Session.CheckResult(Write(_Session.Session,Indicator, ref Unsafe.As(ref tempbuffer[0]), (uint)tempbuffer.Length*8)); } public uint Count { get; } public double[] Value { get => GetData(); set => SetData(value); } } }