C# 中使用非託管源碼(使用指針的源碼)

將寫代碼過程重要的代碼片段收藏起來,如下代碼內容是關於C# 中使用非託管(使用指針的)的代碼。

using System;
using System.Reflection;
using System.Runtime.InteropServices;

[assembly:AssemblyVersion("4.3.2.1")]

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);
   
	[DllImport("version.dll")]
	unsafe public static extern bool VerQueryValue (byte[] pBlock,
		string pSubBlock, out string pValue, out uint len);
	[DllImport("version.dll")]
	unsafe public static extern bool VerQueryValue (byte[] pBlock,
}

public class C 
{
	unsafe public static int Main () 
	{
		try 
		{
			int handle = 0;
			int size =
				Win32Imports.GetFileVersionInfoSize("printversion.exe",
				out handle);

			if (size == 0) return -1;

			byte[] buffer = new byte[size];

			if (!Win32Imports.GetFileVersionInfo("printversion.exe", handle, size, buffer))
			{
				Console.WriteLine("Failed to query file version information.");
				return 1;
			}

			uint len = 0;
			if (!Win32Imports.VerQueryValue (buffer, @"VarFileInfoTranslation", out subBlock, out len))
			{
				Console.WriteLine("Failed to query version information.");
				return 1;
			}

			string spv = @"StringFileInfo" + subBlock[0].ToString("X4") + subBlock[1].ToString("X4") + @"ProductVersion";

			string versionInfo;
			
			if (!Win32Imports.VerQueryValue (buffer, spv, out versionInfo, out len))
			{
				Console.WriteLine("Failed to query version information.");
				return 1;
			}

			Console.WriteLine ("ProductVersion == {0}", versionInfo);
		}
		catch (Exception e) 
		{
			Console.WriteLine ("Caught unexpected exception " + e.Message);
		}
      
		return 0;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章