Python for Delphi problem
Kyle Yancey
kyle at lakeofburningfire.org
Tue Feb 11 19:21:52 EST 2003
Thanks, that's much nicer. I was explicitly copying the string,
because I kept getting an error saying that I was writing to some
memory location. Since the PyString_AsString function returned a
pointer to the internal buffer, I thought that that might be the
problem. I think I've found the real problem though. I was DECREFing
the pyItem returned from pyList. PyList_GetItem returns a borrowed
reference not a new one, so it shouldn't be DECREFed. This code gives
no EAccessViolations and works perfectly. Thanks for all your help.
procedure TForm1.Button1Click(Sender: TObject);
var
pyName, pyModule, pyDict, pyList, pyItem : PPyObject;
Index, pyListSize : Integer;
TempItem: PChar;
begin
pyModule:= nil; pyList:= nil;
pyName := PythonEngine1.PyString_FromString( PChar(Edit1.Text) );
if pyName = nil then
Exit; {raise exception}
try
{import moddule}
pyModule := PythonEngine1.PyImport_Import(pyName);
if pyModule = nil then
Exit; {raise exception}
{Get the module's dictionary}
pyDict := PythonEngine1.PyModule_GetDict(pyModule);
{Get the keys list from the dictionary}
pyList := PythonEngine1.PyDict_Keys(pyDict);
{Get the size of the list}
pyListSize := PythonEngine1.PyList_Size(pyList);
for Index := 0 to pyListSize-1 do
begin
{Get each item in the list}
pyItem := PythonEngine1.PyList_GetItem(pyList, Index);
if pyItem = nil then
Break; {raise exception}
TempItem:= PythonEngine1.PyString_AsString(pyItem);
if TempItem = nil then
Break; {raise exception}
{use implicit conversion of PChar to string}
ListBox1.Items.Add(TempItem);
end;
finally
PythonEngine1.Py_XDECREF(pyList);
PythonEngine1.Py_XDECREF(pyModule);
PythonEngine1.Py_XDECREF(pyName);
end;
end;
More information about the Python-list
mailing list