我正在使用 python4delphi。如何从包装的 Delphi 类函数中返回对象?
代码片段:
我有一个简单的 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 模块名称是 test。
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.