我正在使用python4delphi。如何從包裝的Delphi類函數返回一個對象?Python4Delphi:在函數中返回一個python對象。 (DelphiWrapper)
代碼段:
我有一個簡單的Delphi類,我包裹的Python腳本,對不對?
TSimple = Class
Private
function getvar1:string;
Public
Published
property var1:string read getVar1;
function getObj:TSimple;
end;
...
function TSimple.getVar1:string;
begin
result:='hello';
end;
function TSimple.getObj:TSimple;
begin
result:=self;
end;
我使TPySimple像demo32一樣給予Python代碼的類訪問權限。我的Python模塊名稱是測試。
TPySimple = class(TPyDelphiPersistent)
// Constructors & Destructors
constructor Create(APythonType : TPythonType); override;
constructor CreateWith(PythonType : TPythonType; args : PPyObject); override;
// Basic services
function Repr : PPyObject; override;
class function DelphiObjectClass : TClass; override;
end;
...
{ TPySimple }
constructor TPySimple.Create(APythonType: TPythonType);
begin
inherited;
// we need to set DelphiObject property
DelphiObject := TSimple.Create;
with TSimple(DelphiObject) do begin
end;
Owned := True; // We own the objects we create
end;
constructor TPySimple.CreateWith(PythonType: TPythonType; args: PPyObject);
begin
inherited;
with GetPythonEngine, DelphiObject as TSimple do
begin
if PyArg_ParseTuple(args, ':CreateSimple') = 0 then
Exit;
end;
end;
class function TPySimple.DelphiObjectClass: TClass;
begin
Result := TSimple;
end;
function TPySimple.Repr: PPyObject;
begin
with GetPythonEngine, DelphiObject as TSimple do
Result := VariantAsPyObject(Format('',[]));
// or Result := PyString_FromString(PAnsiChar(Format('()',[])));
end;
而現在的Python代碼:
import test
a = test.Simple()
# try access the property var1 and everything is right
print a.var1
# work's, but..
b = a.getObj();
# raise a exception that not find any attributes named getObj.
# if the function returns a string for example, it's work.
有人投票不用說爲什麼(一些人有壞習慣,我希望我可以低估他們!)我的猜測是,你應該解釋更多關於你的意思(也許是代碼片段),什麼是不工作或者你已經嘗試過的東西。 – 2012-03-19 16:50:11
這個問題對我來說似乎很模糊。缺乏活動支持這種感覺。 – 2012-03-19 19:43:27
好吧,夥計們,拿一些代碼片段。 – 2012-03-19 20:26:55