【发布时间】:2012-03-19 13:40:21
【问题描述】:
我正在使用 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;
我制作了类似于 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;
现在是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.
【问题讨论】:
-
有人投了反对票,但没有说明原因(有些人有一个坏习惯,我希望我能对他们投反对票!)不过我的猜测是你应该更多地解释你的意思(也许是一个代码 sn-p ) 以及什么不起作用或您已经尝试过什么。
-
这个问题对我来说似乎很模糊。缺乏活动支持了这种感觉。
-
好吧伙计们,拿一些代码 sn-ps。
-
乍一看确实很奇怪。更简单的方法是否有效,例如一个返回一个整数?也许它返回指向类本身的指针这一事实使包装器感到困惑——它将如何处理?你如何“让 TPySimple 像 demo32 一样让类访问 python 代码”?您能否链接到他们的文档或显示生成的导入文件中的内容(如果这是人类可读的,我不知道。)
-
这是一个糟糕的文档化组件 (code.google.com/p/python4delphi) 但您可以下载源代码并运行演示,在 demo32 中它们向我们展示了如何在您的 python 脚本中使用 delphi 类,我认为 TPySimple 的代码对我们没有帮助,但现在就在这里。
标签: delphi delphi-xe2 python4delphi