Python4Delphi:在函数中返回python对象.(DelphiWrapper)

Gab*_*eca 5 delphi delphi-xe2 python4delphi

我正在使用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;
Run Code Online (Sandbox Code Playgroud)

我使用了类似于demo32的TPySimple来提供对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;
Run Code Online (Sandbox Code Playgroud)

现在的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.
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 0

根据OP,他在这里找到了答案:http://code.google.com/p/python4delphi/issues/detail ?id=17

(复制粘贴供参考)

你好,

我有一个建议 - 通过利用 D2010(及更高版本)中新的 RTTI(运行时类型信息)功能,使 Delphi 对象轻松地暴露给 python。

目前将一个类暴露给托管的Python代码需要你编写太多的代码(查看demo06),我想如果我们利用新版本的Delphi中的新RTTI功能,这个过程可以改进很多。

例如,查看 Delphi chromium 嵌入式项目,要将任何 Delphi 类的接口暴露给 JavaScript 环境,您所要做的就是注册该类:

// this is your class exposed to JS 
  Test = class 
    class procedure doit(const v: string); 
  end; 

initialization 
// Register your class 
  TCefRTTIExtension.Register('app', Test);

// and in JavaScript code to call that class above:
app.doit(''foo'')', '', 0); 
Run Code Online (Sandbox Code Playgroud)

凉爽的!不是吗?

上述代码摘自:http://groups.google.com/group/delphichromiumembedded/browse_thread/thread/1793e7ca66012f0c/8ab31a5ecdb6bf48 ?lnk=gst&q=JavaScript+return+#

D2010以来引入的一些关于RTTI的介绍: http://robstechcorner.blogspot.com/2009/09/delphi-2010-rtti-basics.html