C++到Delphi的转换问题(关于C++中的指针的)(100分)

  • 主题发起人 wwwxiaopeng
  • 开始时间
W

wwwxiaopeng

Unregistered / Unconfirmed
GUEST, unregistred user!
我用Delphi + DirectDraw编程时遇到一个问题,如下:
C++语言的程序为:
DDSURFACEDESC2 ddsd;
......
int mempitch = ddsd.lPitch;
UCHAR * video_buffer = ddsd.lpSurface;
// plot 1000 random pixels with random colors on the primary surface,
// they will be instantly visible
for (int index=0;
index<1000;
index++)
{
UCHAR color = rand() % 256;
int x = rand() % 640;
int y = rand() % 480;
// plot the pixel
[red]video_buffer[x+y*mempitch][/red] = color;<---问题部分???
} // end for index
其中lpSurface是一个指针(void *)类型,它是DDSD中的一个域,这个指针指向所创建的显示表面所驻留的实际内存,怎样才能把标记为红色的部分变为Pascal语言呢?
这是一个关于怎样把C中的指向数组的指针,用Delphi语言表达出来的问题。
指向数组的指针在Delphi中表示为:
Var FPArray : ^ Array[0..10] of integer;
对吗???
Delphi中的指针和数组的关系大不大?它们之间有怎样的联系?
 
嘿黑......
 
To dcms:
你能回答吗???
 
Delphi的不能在这样直接定义,必须先定义基类型,再定义这基类型的指针。这样指针才能指向正确的位置写、读正确的数据。
另外,Delphi会对数组类型进行范围检查,如果要未知数组个的C++类型,要么取消范围检查,要么定义一个足够大的范围数组。
对于上例,可以定义:
type
TIntArray = array [0.. MaxInt div 16 - 1] of Integer;
PIntArray = ^TIntArray;
var
FPArray : PIntArray;
 
C和Delphi的数组概念有差别.
C中数组等价于指针.就是指向第一个元素的指针.
Delphi中数组是实际的数据.指针和数组是两个不同的概念.非要对应C的数组则要传数组地址

而且Pascal十分严格.类型必须完全匹配.
a:^Integer;
b:^Integer;
会被认为是不同的类型.必须强制转换或者定义一个指针类型
type
PInteger = ^Integer;
a:pInteger;
b:pInteger;
a,b才会是同一个类型.

至于楼主的问题
video_buffer[x+y*mempitch] = color;
有几种实现方式.
1.
Type
PByte=^Byte;
var
video_buffer,Oldvideo_buffer : PByte;//Char指针PChar也一样

......
Oldvideo_buffer := video_buffer;
for i:=0 to ...do
begin
....
video_buffer := Oldvideo_buffer + (x+y*mempitch);
video_buffer^ := color;
end;
2.
Type
TByteArray = array[0..0] of char;
PByteArray = ^TByteArray;
var
video_buffer : PByteArray;

for i:=0 to ...do
begin
....
video_buffer^[x+y*mempitch] := color;//这里是越界访问,所以不能用常量作为数组下标,Delphi编译器会报错.
//VCL里面很多就是通过这种越界访问来实现的
end;
 

Similar threads

顶部