MethodTable内存空间分配中的加法运算方法
来源:优易学  2011-12-3 11:01:37   【优易学:中国教育考试门户网】   资料下载   IT书店
  在分析MethodTable具体分配内存实现的时候,看到了计算MethodTable的大小,然后分配空间的算法。其中有个加法运算实现的非常赞,特地截取出来。
  所有的MethodTable的分配,都是通过methodtable中的一个static方法AllocagteNewMT来实现的,该方法定义如下:
  MethodTable * MethodTable::AllocagteNewMT(EEClass *pClass,
  DWORD dwVtableSlots,
  DWORD dwGCSize,
  DWORD dwNumInterfaces,
  DWORD numGenericArgs,
  DWORD dwNumDicts,
  DWORD cbDict,
  ClassLoader *pClassLoader,
  BaseDomain *pDomain,
  BOOL isInterface,
  BOOL fHasGenericsStaticsInfo,
  BOOL fNeedsRemotableMethodInfo,
  BOOL fNeedsRemotingVtsInfo,
  BOOL fHasThreadOrContextStatics
  , AllocMemTracker *pamTracker
  )
  下面是该方法中计算大小的一段,采用模板来忽略类型带来的影响:
  DWORD cbTotalSize = 0;
  DWORD cbDicts = 0;
  if (!ClrSafeInt<DWORD>::multiply(dwNumDicts, sizeof(TypeHandle*), cbDicts) ||
  !ClrSafeInt<DWORD>::addition((DWORD)size, cbDicts, cbTotalSize) ||
  !ClrSafeInt<DWORD>::addition(cbTotalSize, dwGCSize, cbTotalSize))
  ThrowHR(COR_E_OVERFLOW);
  然后转到addition((DWORD)size, cbDicts, cbTotalSize)的实现,加法的实现如下,加入了对各种情况的严格考虑:
  // Returns true if safe, false on overflow
  static inline bool addition(T lhs, T rhs, T &result)
  {
  //check for T first.
  if(IsSigned())
  {
  //test for +/- combo
  if(!IsMixedSign(lhs, rhs))
  {
  //either two negatives, or 2 positives, not mixed symbols
  if(rhs < 0)
  {
  //two negatives
  if(lhs < (T)(MinInt() - rhs)) //remember rhs < 0
  {
  return false;
  }
  //ok
  }
  else
  {
  //two positives
  if((T)(MaxInt() - lhs) < rhs)
  {
  return false;
  }
  //OK
  }
  }
  //else overflow not possible
  result = lhs + rhs;
  return true;
  }
  else //unsigned, and two symbols is mixed
  {
  if((T)(MaxInt() - lhs) < rhs)
  {
  return false;
  }
  result = lhs + rhs;
  return true;
  }
  }
  其中,涉及到中间调用的几个方法如下:
  static bool IsSigned()
  {
  return( (T)-1 < 0 );
  }
  //Check if lhs and rhs is mixed Sign symbols
  static bool IsMixedSign(T lhs, T rhs)
  {
  return ((lhs ^ rhs) < 0);
  }
  //both of the following should optimize away
  static T MinInt()
  {
  if(IsSigned())
  {
  return (T)((T)1 << (BitCount()-1));
  }
  else
  {
  return ((T)0);
  }
  }
  static T MaxInt()
  {
  if(IsSigned())
  {
  return (T)~((T)1 << (BitCount()-1));
  }
  //else
  return (T)(~(T)0);
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
热门课程培训