不安全的c#代码会导致64位平台上的堆损坏,除非是为x86平台构建的
我有一个简单的util,它使用一些不安全的代码来获取文件版本信息。当我将其编译为混合平台(vs2008/.NET3.5)并部署到64位机器时,我得到了一个堆损坏错误。如果我重新编译为x86,那么一切都正常 这是令人惊讶的,因为我对.NET通用类型系统的理解。我的不安全代码使用指向short的指针和指向字节的指针。由于CTS,这些常见类型在任何平台上的尺寸是否相同?我错过了什么不安全的c#代码会导致64位平台上的堆损坏,除非是为x86平台构建的,c#,64-bit,heap,unsafe,C#,64 Bit,Heap,Unsafe,我有一个简单的util,它使用一些不安全的代码来获取文件版本信息。当我将其编译为混合平台(vs2008/.NET3.5)并部署到64位机器时,我得到了一个堆损坏错误。如果我重新编译为x86,那么一切都正常 这是令人惊讶的,因为我对.NET通用类型系统的理解。我的不安全代码使用指向short的指针和指向字节的指针。由于CTS,这些常见类型在任何平台上的尺寸是否相同?我错过了什么 using System; using System.Reflection; using System.Runtime.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
public class Win32Imports
{
[DllImport("version.dll")]
public static extern bool GetFileVersionInfo(string sFileName,
int handle, int size, byte[] infoBuffer);
[DllImport("version.dll")]
public static extern int GetFileVersionInfoSize(string sFileName,
out int handle);
// The third parameter - "out string pValue" - is automatically
// marshaled from ANSI to Unicode:
[DllImport("version.dll")]
unsafe public static extern bool VerQueryValue(byte[] pBlock,
string pSubBlock, out string pValue, out uint len);
// This VerQueryValue overload is marked with 'unsafe' because
// it uses a short*:
[DllImport("version.dll")]
unsafe public static extern bool VerQueryValue(byte[] pBlock,
string pSubBlock, out short* pValue, out uint len);
}
public class FileInformation
{
// Main is marked with 'unsafe' because it uses pointers:
unsafe public static string GetVersionInformation(string path)
{
// Figure out how much version info there is:
int handle = 0;
int size =
Win32Imports.GetFileVersionInfoSize(path,
out handle);
if (size == 0) return "";
byte[] buffer = new byte[size];
if (!Win32Imports.GetFileVersionInfo(path, handle, size, buffer)) return "";
// Get the locale info from the version info:
short* subBlock = null;
uint len = 0;
if (!Win32Imports.VerQueryValue(buffer, @"\VarFileInfo\Translation", out subBlock, out len)) return "";
// Get the ProductVersion value for this program:
string spv = @"\StringFileInfo\" + subBlock[0].ToString("X4") + subBlock[1].ToString("X4") + @"\ProductVersion";
byte* pVersion = null;
string versionInfo;
if (!Win32Imports.VerQueryValue(buffer, spv, out versionInfo, out len)) return "";
return versionInfo;
}
}
谢谢
所有僵尸的杀手,等待僵尸的末日。。。。。。。
-Jonathan您有什么理由不能为此使用托管类吗?我怀疑它在32位和64位平台上都能正常工作。可能因为平台中的指针是64位的,但您使用的是不安全的,所以转换不正确?另外,请显示p/invoke导入的外观。是的,我可以使用该类型。但是我对这个问题的理解不会有帮助。这不是我要更改的代码(不在我的组中)。链接断开了吗?尝试