32位编译的VSTO插件迁移到64位Office产品中的异常一例

      前段时间,我发布过一篇随笔《VSTO中使用线程钩子响应鼠标键盘事件》,当时的编译环境是32位的,后来在64位的Office中,原本以为会顺利在wow64下兼容运行的,但遗憾的是,启动文档后只要有鼠标键盘消息就会抛出异常。截图如下:

      可想而知,多半是不恰当的数据类型引起的,于是对代码进行调整,在MSDN发现有这样一段描述,引起我的注意:64-bit Applications

 

Many assemblies run identically on both the 32-bit CLR and the 64-bit CLR. However, some programs may behave differently, depending on the CLR, for one or more of the following reasons:

  • Structs that contain members that change size depending on the platform, for example, any pointer type.

  • Pointer arithmetic that includes constant sizes.

  • Incorrect platform invoke or COM declarations that use Int32 for handles instead of IntPtr.

  • Casting IntPtr to Int32.

一开始我并不明白为什么单独把IntPtr指出来,仔细查看IntPtr的类型说明,才明白,原来IntPtr在不同的操作系统下指向的地址大小是不同的,也就是说,64位操作系统下使用64位的Office,它指向的类型是Int64,而并非Int32,所以在我先前的代码中,凡涉及到IntPtr转int的语句,均会出现算术溢出的异常。在了解这些后,所做的改动就比较明确了,为了保证同时在32/64位平台下执行,把IntPtr全部改为int,如果要区别对待的话,应该显式的把IntPtr与Int32或Int64做转换,目标就是使用一致的数据类型。

posted on 2012-04-13 14:53  Bean.Hsiang  阅读(976)  评论(0编辑  收藏  举报