Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Buscar Temas de Hoy Marcar Foros Como Leídos

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 01-02-2006
Victor_TlrSoft Victor_TlrSoft is offline
Registrado
 
Registrado: feb 2006
Posts: 5
Poder: 0
Victor_TlrSoft Va por buen camino
Problemas con punteros

Buenas:

Soy programador en Java, Visual Basic, C++ y ahora por motivos de trabajo me veo obligado a pelearme con Delphi.

Y me encuentro con un problema, que no he sido capaz de solucionar pero que tengo la impresion que se debe a mi corto conocimiento del lenguaje.

Estoy haciendo una DLL que se pueda usar en un entorno Windows desde cualquier lenguaje de programacion, estoy haciendo pruebas con .Net y con VB6.

Y tengo dentro de mi DLL una Unit con el siguiente metodo:
Código Delphi [-]
//***********************************************************************
//*         GET_DOCUMENT_LIST_RESPONSE_DOC                              *
//*                                                                     *
//*  docIndex : PLongInt ==> El indice del documento del que queremos   *
//*                          recuperar los datos                        *
//*                                                                     *
//*  docIdentification : PLongInt <==> El identificador unico del doc   *
//*                                    que estamos recuperando.         *
//*                                                                     *
//*  superState : PChar <==> indica el superestado de los documentos    *
//*                          que solicitamos                            *
//*               - OPEN abiertos                                       *
//*               - CLOSED cerrados                                     *
//*                                                                     *
//*  state : PChar <==> indica el estado de los docs que solicitamos    *
//*               - NEW nuevos                                          *
//*               - DOWNLOADED ya descargados                           *
//*               - DECLINED rechazados                                 *
//*               - ACCEPTED aceptados                                  *
//*               - MODIFIED modificados                                *
//*                                                                     *
//*  format : PChar <==> El formato en que queremos que se nos devuelva *
//*                     el documento.                                   *
//*             - EDI formato edi                                       *
//*             - TXTTLR formato de texto con la estructura de TLR      *
//*             - XMLTLR formato xml con la estructura de TLR           *
//*                                                                     *
//*  submissionDate : PChar <==> La fecha del documento                 *
//*                                                                     *
//*  docNumber : Pchar <==> El identificador del documento propio del   *
//*                         documento y que no guarda relacion con su   *
//*                         identificador en la base de datos           *
//*                                                                     *
//*  docFunction : PChar <==> La funcion del documento independiente de *
//*                           la plataforma y que variara dependiendo   *
//*                           del tipo de documento                     *
//*                                                                     *
//*  companyName : PChar <==> El nombre de la compañia a la que se      *
//*                           dirige o desde la cual se recibe este     *
//*                           documento.                                *
//*                                                                     *
//*  identityCount : PLongInt <==> El numero de identitys que definen   *
//*                                a la compañia que es origen o destino*
//*                                de este documento.                   *
//*                                                                     *
//*  Devuelve los datos generales del documento que le solicitamos en   *
//*  las variables que le pasamos por parametr.                         *
//***********************************************************************
    procedure getDocumentListResponseDoc(const docIndex : PLongInt;
                                         var RdocIdentification : PLongInt;
                                         var RsuperState : PChar;
                                         var Rstate : PChar;
                                         var Rformat : PChar;
                                         var RsubmissionDate : PChar;
                                         var RdocNumber : PChar;
                                         var RdocFunction : PChar;
                                         var RcompanyName : PChar;
                                         var RidentityCount : PLongInt);
    var
      docSend : ddoc;
      docReceived : odoc;
      index : LongInt;
      sDocIdent : LongInt;
      sSState : String;
      sState : String;
      sFormat : String;
      sSubmissionDate : String;
      sDocNumber : String;
      sDocFunction : String;
      sCompanyName : String;
      sIdentityCount : LongInt;
      PdocIdentification:PLongInt;
      PsuperState:PChar;
      Pstate:PChar;
      Pformat:PChar;
      PsubmissionDate:PChar;
      PdocNumber:PChar;
      PdocFunction:PChar;
      PcompanyName:PChar;
      PidentityCount:PLongInt;
    begin
        index := LongInt(docIndex);
        if (receivedDocumentList = nil)then
          begin
            if (sendDocumentList = nil) then
              begin
                strLastMessage := 'No data to recover';
                intLastCode := NO_STORED_DATA;
              end
            else
              begin
                 if ((index > -1) and (index < Length(sendDocumentList))) then
                  begin
                     docSend := sendDocumentList[index];
                     case docSend.state of
                      NEW:sSState:= 'NEW';
                      DOWNLOADED:sSState:= 'DOWNLOADED';
                      DECLINED:sSState:= 'DECLINED';
                      ACCEPTED:sSState:= 'ACCEPTED';
                      MODIFIED:sSState:= 'MODIFIED';
                     end;
                     case docSend.superState of
                      OPEN:sState := 'OPEN';
                      CLOSED:sState := 'CLOSED';
                     end;
                     sDocIdent := docSend.documentId;
                     sFormat := docSend.format;
                     sSubmissionDate := DateTimeToStr(docSend.submissionDate.AsDateTime);
                     sDocNumber := docSend.documentNumber;
                     sDocFunction := docSend.documentFunction;
                     sCompanyName := docSend.destination.companyName;
                     sIdentityCount := Length(docSend.destination.listIdentityID);
                     PdocIdentification:=PLongInt(sDocIdent);
                     PsuperState:=PChar(sSState);
                     Pstate:=PChar(sState);
                     Pformat:=PChar(sFormat);
                     PsubmissionDate:=PChar(sSubmissionDate);
                     PdocNumber:=PChar(sDocNumber);
                     PdocFunction:=PChar(sDocFunction);
                     PcompanyName:=PChar(sCompanyName);
                     PidentityCount:=PLongInt(sIdentityCount);
                     RdocIdentification := PdocIdentification;
                     RsuperState := PsuperState;
                     Rstate := Pstate;
                     Rformat := Pformat;
                     RsubmissionDate := PsubmissionDate;
                     RdocNumber := PdocNumber;
                     RdocFunction := PdocFunction;
                     RcompanyName := PcompanyName;
                     RidentityCount := PidentityCount;
                     strLastMessage := 'OK';
                     intLastCode := TRANSACTION_OK;
                  end
                 else
                  begin
                   strLastMessage := 'Index out of range';
                   intLastCode := NO_DOC_AT_INDEX;
                 end;
            end;
          end
        else
          begin
            if ((index > -1) and (index < Length(receivedDocumentList))) then
              begin
                docReceived := receivedDocumentList[index];
                case docReceived.state of
                  NEW:sSState:= 'NEW';
                  DOWNLOADED:sSState:= 'DOWNLOADED';
                  DECLINED:sSState:= 'DECLINED';
                  ACCEPTED:sSState:= 'ACCEPTED';
                  MODIFIED:sSState:= 'MODIFIED';
                end;
                case docReceived.superState of
                  OPEN:sState := 'OPEN';
                  CLOSED:sState := 'CLOSED';
                end;
                sDocIdent := docReceived.documentId;
                sFormat := docReceived.format;
                sSubmissionDate := DateTimeToStr(docReceived.submissionDate.AsDateTime);
                sDocNumber := docReceived.documentNumber;
                sDocFunction := docReceived.documentFunction;
                sCompanyName := docReceived.origin.companyName;
                sIdentityCount := Length(docReceived.origin.listIdentityID);
                PdocIdentification:=PLongInt(sDocIdent);
                PsuperState:=PChar(sSState);
                Pstate:=PChar(sState);
                Pformat:=PChar(sFormat);
                PsubmissionDate:=PChar(sSubmissionDate);
                PdocNumber:=PChar(sDocNumber);
                PdocFunction:=PChar(sDocFunction);
                PcompanyName:=PChar(sCompanyName);
                PidentityCount:=PLongInt(sIdentityCount);
                RdocIdentification := PdocIdentification;
                RsuperState := PsuperState;
                Rstate := Pstate;
                Rformat := Pformat;
                RsubmissionDate := PsubmissionDate;
                RdocNumber := PdocNumber;
                RdocFunction := PdocFunction;
                RcompanyName := PcompanyName;
                RidentityCount := PidentityCount;
                strLastMessage := 'OK';
                intLastCode := TRANSACTION_OK;
              end
            else
              begin
                strLastMessage := 'Index out of range';
                intLastCode := NO_DOC_AT_INDEX;
              end;
            end;
        end;
La idea de este metodo es que una llamada SOAP me devuelva los valores y yo los almacene en estos Punteros que le paso por parametro y los recupere desde la aplicacion cliente que usa esta DLL.

Pero me pasa algo muy curioso, en principio si depuro los valores dentro del codigo de la DLL estan bien pero al devolver los punteros estan con algunos caracteres extraños.

Y es mas, cuando los asigno por ejemplo a un campo de texto tipo TEdit de
la siguiente manera :
Código Delphi [-]
 
Edit1.text := String();
los valores de los otros punteros se van modificando mientras voy realizando las asignaciones y el valor que tenian cuando la funcion me devolvio se va modificando sin yo hacer nada mas que la asignacion que pongo arriba.

Ademas me aparecen los valores de unos en otros sin yo haberselos asignado.

Este es el metodo que uso para invocarlo :
Código Delphi [-]
 
procedure TTestDllForm.TestGetDocListRespDocClick(Sender: TObject);
var
  index : Plongint;
  SdocIdentification : plongint;
  SsuperState : Pchar;
  Sstate : Pchar;
  Sformat : Pchar;
  SsubmissionDate : Pchar;
  SdocNumber : Pchar;
  SdocFunction : Pchar;
  ScompanyName : Pchar;
  SidentityCount : plongint;

begin
  SdocIdentification := nil;
  SsuperState := nil;
  Sstate := nil;
  Sformat := nil;
  SsubmissionDate := nil;
  SdocNumber := nil;
  SdocFunction:= nil;
  ScompanyName := nil;
  SidentityCount := nil;
   index := PLongInt(StrToInt(txtGetDocListRespDoc.text));
  getDocumentListResponseDoc(index,
                              SdocIdentification,
                              SsuperState,
                              Sstate,
                              Sformat,
                              SsubmissionDate,
                              SdocNumber,
                              SdocFunction,
                              ScompanyName,
                              SidentityCount);
   txtIdGetDocListRespDoc.Text := IntToStr(LongInt(SdocIdentification));
   txtSSGetDocListRespDoc.Text := String(SsuperState);
   txtSGetDocListRespDoc.Text := String(Sstate);
   txtGetDocListRespDocFormat.Text := String(Sformat);
   txtGetDocListRespDocDate.Text := String(Pchar(SsubmissionDate));
   txtGetDocListRespDocNum.Text := String(Pchar(SdocNumber));
   txtGetDocListRespDocFunc.Text := String(Pchar(SdocFunction));
   txtGetDocListRespDocComp.Text := String(Pchar(ScompanyName));
   txtGetDocListRespDocIdent.Text := IntToStr(LongInt(SidentityCount));
  end;
Supongo que sera una chorrada fruto de mi desconocimiento pero no he sido capaz de arreglarlo. Cualquier ayuda sera bien recibida. Muchas gracias.

Última edición por jmariano fecha: 01-02-2006 a las 15:07:50.
Responder Con Cita
  #2  
Antiguo 01-02-2006
Avatar de seoane
[seoane] seoane is offline
Miembro Premium
 
Registrado: feb 2004
Ubicación: A Coruña, España
Posts: 3.717
Poder: 24
seoane Va por buen camino
El problema es que estas devolviendo un puntero a una variable local, la memoria que corresponde a esa variable es liberada al terminar. Y aunque mantiene parte de la informacion que contenia durante un poco de tiempo, aparecen caracteres estraños y va siendo reemplazada por el contenido de otras variables.
Responder Con Cita
  #3  
Antiguo 01-02-2006
Victor_TlrSoft Victor_TlrSoft is offline
Registrado
 
Registrado: feb 2006
Posts: 5
Poder: 0
Victor_TlrSoft Va por buen camino
ME podrias poner un ejemplo por favor de como lo harias tu? SI no te importa, ya he comentado que soy nuevo y he de hacerme un poquito a las convenciones del lenguaje.

Muchas gracias de antemano.
Responder Con Cita
  #4  
Antiguo 01-02-2006
Avatar de seoane
[seoane] seoane is offline
Miembro Premium
 
Registrado: feb 2004
Ubicación: A Coruña, España
Posts: 3.717
Poder: 24
seoane Va por buen camino
Podemos hacerlo de forma parecida a como se hace en C. Reservamos una porcion de memoria, y copiamos el contenido del string en ella.

Donde tu haces
Código:
Pstate:=PChar(sState);
Yo haria
Código:
GetMem(Pstate,lenght(sState)+1);
StrCopy(Pstate,PChar(sState));

Y recuerda que despues de usar el valor devuleto hay que liberar la memoria que ya no necesitamos.

Código:
txtSSGetDocListRespDoc.Text := String(SsuperState);
FreeMem(Sstate);
El codigo acabo de escribirlo ahora sobre la marcha y espero no haberme equivocado, de todas formas ya te puedes hacer una idea de como se haria.
Responder Con Cita
  #5  
Antiguo 01-02-2006
Victor_TlrSoft Victor_TlrSoft is offline
Registrado
 
Registrado: feb 2006
Posts: 5
Poder: 0
Victor_TlrSoft Va por buen camino
Muy bien, funciona!! Solo tengo 2 pegas
La primera es que cuando hago el FreeMem me da un casque .. realmente hace falta o existe un garbage collector como en JAva que se encarga de recoger la basura?

La segunda es que esto se haya dentro de una DLL y por ejemplo en VB6 no existe la posibilidad de hacer el FreeMem, habria alguna otra posibilidad

De todas maneras muchisimas gracias por la ayuda ... creo que ya entiendo lo que estaba pasando, mola esto de empezar con un lenguaje nuevo.
Responder Con Cita
Respuesta


Herramientas Buscar en Tema
Buscar en Tema:

Búsqueda Avanzada
Desplegado

Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Problemas con instalacion y archivo idr20009.dll allende Varios 0 19-01-2006 15:46:33
Problemas al Empaquetar una aplicación con... oracle Varios 1 26-07-2005 15:46:22
Problemas Access, DbImage - Objeto OLE jsc Conexión con bases de datos 3 27-01-2005 21:41:37
problemas con campos y sum Giniromero SQL 3 22-12-2003 20:40:45


La franja horaria es GMT +2. Ahora son las 06:41:49.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi