2013-08-25 112 views
0

我正在嘗試在C++ Builder應用程序中使用SuperObject進行JSON編組。使用C++ Builder類型的Delphi泛型

超對象有一些通用的功能,以幫助這一點:

TSuperRttiContext = class 
    ... 
    function AsType<T>(const obj: ISuperObject): T; 
    function AsJson<T>(const obj: T; const index: ISuperObject = nil): ISuperObject; 
    end; 

在生成.HPP,它們出現的了。

class PASCALIMPLEMENTATION TSuperRttiContext : public System::TObject 
{ 
    ... 
    template<typename T> T __fastcall AsType(const _di_ISuperObject obj); 
    template<typename T> _di_ISuperObject __fastcall AsJson(const T obj, const _di_ISuperObject index = _di_ISuperObject()); 
}; 

目前爲止還不錯。我可以編譯這樣的代碼

TMyObject * myObject = ...; 
_di_ISuperObject obj = superRttiContext->AsJson(myObject); 

String s = obj->AsString(); 

但是,我無法鏈接它。現在

[ILINK32 Error] Error: Unresolved external 'System::DelphiInterface<Superobject::ISuperObject> __fastcall Superobject::TSuperRttiContext::AsJson<TMyObject *>(const TMyObject * const, const System::DelphiInterface<Superobject::ISuperObject>)' referenced from C:\FOO.OBJ 

,這並不完全出乎意料:該Embarcadero DocWiki says this will happen如果模板未在德爾福代碼實例化。

但是,這裏的問題 - TMyObjectC++對象從TObject後裔,所以我不能看到如何實例從Delphi代碼模板。

任何想法?

+0

您可以在C++中使用JSON讀寫器;請參閱http://stackoverflow.com/questions/3512650/fastest-json-reader-writer-for-c –

+0

你可以在Delphi中創建一個類似的對象來代替TMyObject,然後使用生成的C++等價物。 hpp文件? – nachbar

回答

2

你可以嘗試:

一)在Delphi中,創建TSuperRttiContext的適配器。

type 
    TAdapterSuperObject<T : class> = class 
    constructor Create(); 
    destructor Destroy(); override; 
    function ObjectToJson(value : T) : String; 
    function JsonToObject(value : String) : T; 
    end; 

function TAdapterSuperObject<T>.JsonToObject(value: String): T; 
var 
    iso : ISuperObject; 
    ctx : TSuperRttiContext; 
begin 
    ctx := TSuperRttiContext.Create; 
    try 
    try 
    iso := SO(value); 
     Result := ctx.AsType<T>(iso) 
    except 
     on e: Exception do 
     raise Exception.Create('JsonToObject error: ' + e.Message); 
    end; 
    finally 
    iso := Nil; 
    ctx.Free; 
    end; 
end; 

function TAdapterSuperObject<T>.ObjectToJson(value: T): String; 
var 
    ctx : TSuperRttiContext; 
begin 
    ctx := TSuperRttiContext.Create; 
    try 
    try 
    Result := ctx.AsJson<T>(value).AsString; 
    except 
     on e: Exception do 
     raise Exception.Create('ObjectToJson error: ' + e.Message); 
    end; 
    finally 
    ctx.Free; 
    end; 
end; 

b)使用適配器來聲明你的類和C++

type 
    TAdapterInfo = class(TAdapterSuperObject<TInfo>); 

C)最後使用它們,在C++調用適配器:

TAdapterSuperObject__1<TInfo*>* adapterInfo = new TAdapterSuperObject__1<TInfo*>(); 
... 
adapterCliente->ObjectToJson(aInfo); 
... 

基本上是這樣的想法,我在C++中使用和使用Delphi泛型。

+0

謝謝 - 這給了我一些思考!在步驟B中,這是否意味着你可以實例化一個只是前向聲明的C++類的Delphi模板? – Roddy