C#调用delphi生成的dll获取CPU序列号(一)

        不知道大家有没有发现,C#调用WMI取得的CPU序列号跟调用汇编指令取得的CPU序列号完全不一样,网上有很多关于采用C#调用WMI来获取CPU序列号的方法,一般都是通过查找Win32_Processor类的ProcessorId成员来获取。msdn对ProcessorId是这样描述的:

ProcessorId

    Data type: string
    Access type: Read-only

    Processor information that describes the processor features. For an x86 class CPU, the field format depends on the processor support of the CPUID instruction. If the instruction is supported, the property contains 2 (two) DWORD formatted values. The first is an offset of 08h-0Bh, which is the EAX value that a CPUID instruction returns with input EAX set to 1. The second is an offset of 0Ch-0Fh, which is the EDX value that the instruction returns. Only the first two bytes of the property are significant and contain the contents of the DX register at CPU reset—all others are set to 0 (zero), and the contents are in DWORD format.

        从上面这段文字里,我们可以看到有跟寄存器相关的名词 EAX、EDX,所以我们也可以调用汇编指令来获取CPU的序列号。在这里我们就用delphi来生成获取CPU序列号的dll。在用delphi调用汇编指令之前,我们先做一个小小的例子来看看C#是如何调用delphi的dll并传递参数的。

        1、在delphi7下新建一个dll wizard,然后给工程取名CpuInfo,代码如下:

library CpuInfo;

uses
  SysUtils,
  Classes;

{$R *.res}

//求和,并返回结果
function Add(i:integer;j:integer):integer;
begin
  Result:=i+j;
end;

procedure GetString(i:integer;j:integer;value:PChar);stdcall;
var
  s:string;
  n:integer;
  p:PChar;
begin
  n:=Add(i,j);
  s:=inttostr(n);
  s:=Concat('The result is: ',s);
  p:=PChar(s);   //不能直接用value:=PChar(s)给参数赋值
  StrCopy(value,p);  //而应该用strcopy函数给参数赋值
end;
exports
  GetString;

begin
end.

       2、编译,生成CpuInfo.dll,然后把dll文件复制到C#项目的bin\debug文件夹下。

       3、在C#项目里先引用dll,然后调用GetString方法,最后得到计算结果,代码如下:

        /// <summary>
        /// 引用dll
        /// </summary>
        /// <param name="i"></param>
        /// <param name="j"></param>
        /// <param name="value"></param>
        [DllImport("CpuInfo.dll")]
        public static extern void GetString(int i, int j, StringBuilder value);

        //调用dll
        StringBuilder value = new StringBuilder(256); //注意,value参数对应的是pchar类型的指针变量,所以此处一定要指定参数的大小
        GetString(100, 11, value);
        Console.WriteLine(value.ToString());
        4、运行C#程序,得到的输出结果是The result is: 111

        到此,我们完成了一个简单的C#调用delphi生成的dll的实例,在下一节,我们将演示如何用delphi获取CPU的序列号。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值