将Python对象变为变体

时间:2017-03-20 15:37:01

标签: python class delphi python4delphi

我正在使用Python4Delphi

我有一个python文件,类在其上声明如下:

class Student:
  SName = "MyName"
  SAge = 26

  def GetName(self):
    return SName

  def GetAge(self):
    return SAge

我希望得到这个类的参考,并使用我的Delphi代码访问它的字段或方法

我在这里找到了一个例子: http://www.atug.com/andypatterns/pythonDelphiTalk.htm

但是当我尝试这样做的时候会出现错误: "不支持此类界面"

这是我的Delphi代码:

var
 Err : Boolean;
 S : TStringList;
 MyClass : OLEVariant;
 PObj : PPyObject;
begin
 ...

 S := TStringList.Create;
 try
  S.LoadFromFile(ClassFileEdit.Text);
  Err := False;
  try
   PyEngine.ExecStrings(S);
  except
   on E:Exception do
    begin
     Err := True;

     MessageBox(Handle, PChar('Load Error : ' + #13 + E.Message), '', MB_OK+MB_ICONEXCLAMATION);
    end;
  end;
 finally
  S.Free;
 end;

 if Err then
  Exit;

 Err := False;
 try
  try
   PyEngine.ExecString('ClassVar.Value = Student()');
  except
   on E:Exception do
    begin
     Err := True;

     MessageBox(Handle, PChar('Class Name Error : ' + #13 + E.Message), '', MB_OK+MB_ICONEXCLAMATION);
    end;
  end;
 finally
  if not Err then
   begin
    PObj := ClassDelphiVar.ValueObject;
    MyClass := GetAtom(PObj);
    GetPythonEngine.Py_XDECREF(PObj);

    NameEdit.Text := MyClass.GetName();
    AgeEdit.Text := IntToStr(MyClass.GetAge());
   end;
 end;

此行发生错误:

NameEdit.Text := MyClass.GetName();

似乎MyClass没有填充学生对象

我经常搜索,发现GetAtom在新版本中已被弃用,但我怎么能以另一种方式做到这一点?

  • ClassDelphiVar是一个TPythonDelphiVar组件,带有" ClassVar"作为VarName

1 个答案:

答案 0 :(得分:1)

我找到答案,我会在这里发帖可能对某人有帮助

在表单上放置一个PythonDelphiVar组件并设置它的OnExtGetDataOnExtSetData事件,如下代码:

procedure TMainFrm.ClassDelphiVarExtGetData(Sender: TObject;
  var Data: PPyObject);
begin
 with GetPythonEngine do
   begin
     Data := FMyPythonObject;
     Py_XIncRef(Data); // This is very important
   end;
end;

procedure TMainFrm.ClassDelphiVarExtSetData(Sender: TObject; Data: PPyObject);
begin
 with GetPythonEngine do
  begin
   Py_XDecRef(FMyPythonObject); // This is very important
   FMyPythonObject := Data;
   Py_XIncRef(FMyPythonObject); // This is very important
  end;
end;

我们应该注意Python对象的引用计数

FMyPythonObject在Form的类的公共部分中声明为PPyObject变量

现在,如果我们在Python模块中运行此脚本:

ClassVar.Value = MyClass()

ClassVar是PythonDelphiVar组件的VarName)

然后我们可以像这样得到Python对象的属性:

var
 PObj : PPyObject;
begin
 ...
 PObj := GetPythonEngine.PyObject_GetAttrString(FMyPythonObject, PAnsiChar(WideStringToString('AttrName', 0)));
 AttrValueEdit.Text := GetPythonEngine.PyObjectAsString(PObj);
 ...
end

...

function WideStringToString(const Source: UnicodeString; CodePage: UINT): RawByteString;
var
 strLen: Integer;
begin
 strLen := LocaleCharsFromUnicode(CodePage, 0, PWideChar(Source), Length(Source), nil, 0, nil, nil);
 if strLen > 0 then
  begin
   SetLength(Result, strLen);
   LocaleCharsFromUnicode(CodePage, 0, PWideChar(Source), Length(Source), PAnsiChar(Result), strLen, nil, nil);
   SetCodePage(Result, CodePage, False);
  end;
end;