我正在使用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在新版本中已被弃用,但我怎么能以另一种方式做到这一点?
答案 0 :(得分:1)
我找到答案,我会在这里发帖可能对某人有帮助
在表单上放置一个PythonDelphiVar组件并设置它的OnExtGetData
和OnExtSetData
事件,如下代码:
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;