You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Virtual Pascal中如何比较指针?转换汇编代码报错求助

Virtual Pascal指针比较问题解决方案

在转换包含内联汇编的Virtual Pascal过程时,遇到指针比较的编译错误。以下代码的while (P1 < P2)语句会报错:Operand types do not match operator

错误代码示例:

procedure ReverseBytes(var V; Size : Word);
{-Reverse the ordering of bytes from V[1] to V[Size]. Size must be >= 2.}
var
    P1, P2 : ^Byte;
    PT : Byte;
begin
    P1 := @V;
    P2 := P1;
    Inc(P2, Size-1);
    
    while (P1 < P2) do
    begin
        PT := P1^;
        P1^ = P2^;  // 此处语法错误,应为 :=
        ^P2 := PT;   // 此处语法错误,应为 P2^
        Inc(P1);
        Dec(P2);
    end;
end;

问题核心:如何在Virtual Pascal中比较指针本身(而非指针指向的内容)?已知GNU Pascal等变体支持类似C语言的直接指针比较,但Virtual Pascal不支持这种写法。


解决方案

Virtual Pascal对类型检查非常严格,不允许直接比较指针类型。需要将指针显式转换为整数类型(比如Cardinal,对应32位无符号内存地址),通过比较地址的数值来实现指针比较。同时需要修正代码中的两处语法错误:赋值运算符应为:=而非=,指针取值应写为P2^而非^P2。

修改后的正确代码:

procedure ReverseBytes(var V; Size : Word);
{-Reverse the ordering of bytes from V[1] to V[Size]. Size must be >= 2.}
var
    P1, P2 : ^Byte;
    PT : Byte;
begin
    P1 := @V;
    P2 := P1;
    Inc(P2, Size-1);
    
    while Cardinal(P1) < Cardinal(P2) do  // 转换为Cardinal后比较地址数值
    begin
        PT := P1^;
        P1^ := P2^;  // 修正赋值运算符
        P2^ := PT;   // 修正指针取值写法
        Inc(P1);
        Dec(P2);
    end;
end;

说明

指针本质上是内存地址的数值表示,将其转换为Cardinal(或对应平台的整数类型)后,就能进行数值大小比较,从而判断两个指针在内存中的位置关系。

内容的提问来源于stack exchange,提问作者user3161924

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:45:43