2

如何通过datasnap传输带有TMemoryStream的TObject?

TMyObject = class(TBizObject)
  FText: TMemoryStream;  <-- Content not sent
  ...
end

在服务器端

TServerMethods.GetMyClass(const AId: Integer): TMyObject
begin
  Result := TMyObject.find(AId);
end;

在客户端 TMyObject 正确解组,但 FText 内容为空。

TMemoryStream Json 内容

"FText": {
        "type":"System.Classes.TMemoryStream",
        "id":2,
        "fields":{
            "FCapacity":16384,
            "FSize":11788,
            "FPosition":11788
        }
    }
4

1 回答 1

5

关键是使用字段类型创建 TConverterEvent 和 TReverterEvent *。没有源代码很难找到解决方案。

procedure RegisterDatasnapConvertersAndReverters;
var
  LConverter: TConverterEvent;
  LReverter: TReverterEvent;
begin
  LConverter := TConverterEvent.Create(TMemoryStream, '*' {FIELD_ANY});
  LConverter.TypeStringConverter := function (Data: TObject): string
    var
      stream: TMemoryStream;
    begin
      stream := TMemoryStream(Data);
      stream.Position := 0;
      Result := EncodeBase64(stream.Memory, stream.Size);
    end;
  TJSONConverters.AddConverter(LConverter);

  LReverter := TReverterEvent.Create(TMemoryStream, '*' {FIELD_ANY});
  LReverter.TypeStringReverter := function(Data: string): TObject
    var
      bytes: TBytes;
    begin
      bytes := DecodeBase64(Data);
      Result := TMemoryStream.Create;
      if nil <> bytes then
        TMemoryStream(Result).WriteBuffer(bytes[0], Length(bytes));
    end;
  TJSONConverters.AddReverter(LReverter);
end;

initialization
  RegisterDatasnapConvertersAndReverters;
于 2012-04-23T10:46:28.120 回答