Embedding Python: Creating Python Class from Application

Discussion in 'Python' started by Kakacek, Jan 12, 2006.

  1. Kakacek

    Kakacek Guest

    Hello All,

    Let's say I have a following python code:

    class hw_class:
    def __init__(self):
    pass
    def hello_world(self):
    print 'Hello World!'
    create_instance('hw_class', 'hw')
    hw.hello_world()
    hw = None

    The 'create_instance' function should be implemented in the application
    (powered by Delphi - P4D) which is embedding the Python.dll.

    I am trying to do this for some time having no success. I am missing
    these informations:
    1. How to register global python variable from application which is
    embedding python?
    2. How to assign this variable with the class instance.
    3. How to create the instance of class which is unknown at the compile
    time.

    Could someone supply the (C/Pascal) code fragment for this?

    Thanx,

    Jiri.
     
    Kakacek, Jan 12, 2006
    #1
    1. Advertisements

  2. Kakacek

    Kakacek Guest

    In the mean time I did this. It works however, it creates memory leaks.
    Any idea what could be wrong?

    procedure TForm1.PyCreateInstance(Sender: TObject; PSelf, Args:
    PPyObject;
    var Result: PPyObject);
    var
    BClassName: PChar;
    BInstName: PChar;
    //
    BB: Boolean;
    BModule: PPyObject;
    BClass: PPyObject;
    BInstance: PPyObject;
    begin
    // create_instance
    PE.PyArg_ParseTuple(Args, 'ss:create_instance', [@BClassName,
    @BInstName]);
    PE.CheckError;
    // Find module
    BModule := PE.FindModule('__main__');
    PE.CheckError;
    if BModule <> nil then begin
    // Find class object in the module
    BClass := PE.PyObject_GetAttrString(BModule, BClassName);
    PE.CheckError;
    if BClass <> nil then begin
    // Check it really is a class object
    BB := PE.PyClass_Check(BClass);
    PE.CheckError;
    if BB then begin
    // Calling the class object (to create a new instance)
    BInstance := PE.PyObject_CallObject(BClass, nil);
    PE.CheckError;
    if BInstance <> nil then begin
    // Add the instance to the module object
    PE.PyObject_SetAttrString(BModule, BInstName, BInstance);
    PE.CheckError;
    end;
    end;
    PE.Py_DECREF(BClass);
    end;
    end;
    //
    Result := PE.ReturnNone;
    PE.CheckError;
    end;
     
    Kakacek, Jan 12, 2006
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.