我在用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在新版本中是不受欢迎的,但是我如何能够以另一种方式做到这一点呢?
发布于 2017-04-18 13:18:05
我找到了答案,我会在这里发帖可能对某人有帮助
在表单上放置一个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声明为窗体类的公共部分中的PPyObject变量
现在,如果我们在out Python模块中运行这个脚本:
ClassVar.Value = MyClass()(ClassVar是VarName of PythonDelphiVar组件)
然后,我们可以获得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;https://stackoverflow.com/questions/42907805
复制相似问题