VariantToStream 执行出错 ( 积分: 100 )

  • 主题发起人 主题发起人 DickWu
  • 开始时间 开始时间
D

DickWu

Unregistered / Unconfirmed
GUEST, unregistred user!
procedure VariantToStream (const v : olevariant; Stream : TMemoryStream);
var
p : pointer;
begin
Stream.Position := 0;
Stream.Size := VarArrayHighBound (v, 1) - VarArrayLowBound (v, 1) + 1;
p := VarArrayLock (v);
Stream.Write (p^, Stream.Size);
VarArrayUnlock (v);
Stream.Position := 0;
end;

执行到
Stream.Size := VarArrayHighBound (v, 1) - VarArrayLowBound (v, 1) + 1;
这句的时候出错,分解上面的语句后,发现是执行
VarArrayHighBound (v, 1)的时候出错,然后函数退出了,

出错信息是似乎是 InValid argument
 
procedure VariantToStream (const v : olevariant; Stream : TMemoryStream);
var
p : pointer;
begin
Stream.Position := 0;
Stream.Size := VarArrayHighBound (v, 1) - VarArrayLowBound (v, 1) + 1;
p := VarArrayLock (v);
Stream.Write (p^, Stream.Size);
VarArrayUnlock (v);
Stream.Position := 0;
end;

执行到
Stream.Size := VarArrayHighBound (v, 1) - VarArrayLowBound (v, 1) + 1;
这句的时候出错,分解上面的语句后,发现是执行
VarArrayHighBound (v, 1)的时候出错,然后函数退出了,

出错信息是似乎是 InValid argument
 
OleVariant改用Variant类型呢?
 
如果一个Variant变量没有被VarArrayCreate语句初始化,VarArrayHighBound (v, 1)这条语句将产生执行异常。
VarArrayHighBound (v, 1) - VarArrayLowBound(v, 1) + 1返回长度是无效的,
它是返回Variant数组的长度不是整个Variant变量的实际长度
给你一个例子,文件可以任意:
var
Form1: TForm1;
V: OleVariant;
implementation

{$R *.dfm}
procedure VariantToStream(const Data: OleVariant; Stream: TStream);
var
p: Pointer;
begin
p := VarArrayLock(Data);
try
Stream.Write(p^, VarArrayHighBound(Data,1) + 1); //assuming low bound = 0
finally
VarArrayUnlock(Data);
end;
end;

function StreamToVariant(Stream: TStream): OleVariant;
var
p: Pointer;
begin
Result := VarArrayCreate([0, Stream.Size - 1], varByte);
p := VarArrayLock(Result);
try
Stream.Position := 0; //start from beginning of stream
Stream.Read(p^, Stream.Size);
finally
VarArrayUnlock(Result);
end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
Mystream: TFileStream;
begin
MyStream := TFileStream.Create('e:/aaa.txt',fmOpenRead);
MyStream.Position := 0;
V := StreamToVariant(MyStream);
MyStream.Free;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
Mystream: TFileSTream;
begin
MyStream := TFileSTream.Create('e:/bbb.txt',fmCreate);
VariantToStream(V,MyStream);
MysTream.Free;
end;
 
该olevariant变量是从一个OCX控件的方法参数中回传的bmp图像, 我用该控件单独写了个测试程序,使用相同的VariantToStream函数代码,却可以正常工作
测试程序use的单元和我实际出错时使用的单元几乎一致,我专门做了比较.

郁闷死我了~~~~~~~
 
已经解决,重新生成一个单元,Copy原来的代码过去就行
 
后退
顶部