Use Delphi serialization via JSON with C++

泪湿孤枕 提交于 2020-01-16 18:14:09

问题


Knowing that C++ does not have reflection I had a look at Delphi techniques and found an example using the REST.JSON library for serialization: Convert Object to JSON ...

Now I would like to use a Delphi class, which can be serializied and deserialized with the provided methods, in my C++ code:

TFoo = class(TObject)
private
public
  Fa: Integer;
  Fb: Double;
end;

In the C++ unit the class is serialized and deserialized like this:

#include <REST.Json.hpp>
#include "TestJson.hpp" //Contains TFoo

TFoo* foo = new TFoo(); 
foo->Fa = 1;
foo->Fb = 0.999;
String json = TJson::ObjectToJsonString(foo); //Works
delete foo;
foo = TJson::JsonToObject<TFoo*>(json); //Doesn't work
delete foo;

The serialization works fine, but calling TJson::JsonToObjectleads to a linker error. A bit of research revealed that this has to be expected when using Delphi generics with C++ How to Handle Delphi Generics in C++.

It says that instantiation has to be done on the Delphi side, so I added a function to the Delphi unit:

function GetObj(Json: string) : TFoo;
begin
  Result := TJson.JsonToObject<TFoo>(Json);
end; 

After this linking works, but when running the code the following error occurs:

... EConversionError ...cannot intantiate type TestJson.TFoo ...

When the function is called from an other Delphi unit the it works fine.

Debugging the Embarcadero code has shown that this happens due to missing type information when.

Is there any way to get this working?

来源:https://stackoverflow.com/questions/55025516/use-delphi-serialization-via-json-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!