语言差异引起的问题解决一例

在2004DevDay中,介绍的SmartClient技术以及其DataProtection技术,刚好目前的项目计划使用这样的技术。

我是使用C#编码的,但IssueVission是用VB.Net写的,这难不倒我,毕竟BASIC还是自己的入门语言,VB和VBScript更是用了不少,翻译吧!

一切都进展顺利……运行,错误出来了,DataProtection类的Encrypt和Decrypt两个函数报告溢出错误,跟踪进去查看,发现是调用DPAPI产生异常,麻烦了,比对代码没有问题呀?

实在解决不了了,就用VB的现成代码写了一个独立的类来实现这个功能。

今天把Reflector弄来反编译,问题找着了。

在翻译过程中,一切都没有什么大问题,问题在下面的函数:

VB.Net:
 ' helper method that gets data from a DATA_BLOB,
 ' copies data from unmanaged memory to managed
 Private Shared Function GetBlobData(ByRef blob As Win32.DATA_BLOB) As Byte()
  ' return an empty string if the blob is empty
  If blob.pbData.ToInt32() = 0 Then Return Nothing

  ' copy information from the blob
  Dim data(blob.cbData - 1) As Byte
  Marshal.Copy(blob.pbData, data, 0, blob.cbData)
  Win32.LocalFree(blob.pbData)

  Return data
 End Function

翻译后的C#:
  //helper method that gets data from a DATA_BLOB,
  //copies data from unmanaged memory to managed
  private static byte[] GetBlobData(ref Win32.DATA_BLOB blob)
  {
   //return an empty string if the blob is empty
   if(blob.pbData.ToInt32() == 0)
    return null;
   //copy information from the blob
   byte[] data=new byte[blob.cbData-1];
   Marshal.Copy(blob.pbData, data, 0, blob.cbData);
   Win32.LocalFree(blob.pbData);
   return data;
  }
从上面的代码来看,应该是没有问题的,事实上也没有什么问题,但运行结果就是有问题,下面是从正确的VB反编译的C#编码:
private static byte[] GetBlobData(ref DATA_BLOB blob)
{

if (blob.pbData.ToInt32() == 0)
{
return null;
}
byte[] numArray1 = new byte[((blob.cbData - 1) + 1)];
Marshal.Copy(blob.pbData, numArray1, 0, blob.cbData);
Win32.LocalFree(blob.pbData);
return numArray1;
}

呵呵,问题这么简单:
新建byte[]时少分配了一个字节。

posted @ 2004-06-05 08:48  无之无  阅读(741)  评论(3编辑  收藏  举报