问题
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::JsonToObject
leads 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