Python4Delphi: Returning a python object in a function. (DelphiWrapper)

Posted by Gabriel Fonseca on Stack Overflow See other posts from Stack Overflow or by Gabriel Fonseca
Published on 2012-03-19T13:40:21Z Indexed on 2012/03/21 5:30 UTC
Read the original article Hit count: 281

I am using python4delphi. ow can I return an object from a wrapped Delphi class function?

Code Snippet:

I have a simple Delphi Class that i wrapped to Python Script, right?

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;

I made the TPySimple like the demo32 to give class access to the python code. My python module name is test.

TPyDado = 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;
...

{ TPyDado }

constructor TPyDado.Create(APythonType: TPythonType);
begin
  inherited;
  // we need to set DelphiObject property
  DelphiObject := TDado.Create;
  with TDado(DelphiObject) do begin
  end;
  Owned := True; // We own the objects we create
end;

constructor TPyDado.CreateWith(PythonType: TPythonType; args: PPyObject);
begin
  inherited;
  with GetPythonEngine, DelphiObject as TDado do
    begin
      if PyArg_ParseTuple( args, ':CreateDado' ) = 0 then
        Exit;
    end;
end;

class function TPyDado.DelphiObjectClass: TClass;
begin
  Result := TDado;
end;

function TPyDado.Repr: PPyObject;
begin
  with GetPythonEngine, DelphiObject as TDado do
    Result := VariantAsPyObject(Format('',[]));
    // or Result := PyString_FromString( PAnsiChar(Format('(%d, %d)',[x, y])) );
end;

And now the python code:

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.

© Stack Overflow or respective owner

Related posts about delphi

Related posts about delphi-xe2