00.Forums
Objet : Callback Functions - Nada acontece preciso de ajuda!
Started by cafedotnet at 10-31-2005 12:53 PM. Topic has 1 replies.
  Page 1 of 1 (2 items)

cafedotnet
cafedotnet
Added: 12:53 PM on 10/31/2005

Não acontece nada na função callback abaixo:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;

namespace WindowsApplication1
{
 /// <summary>
 /// Summary description for Form1.
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  // Declaring Delegate for Callback Function
  // note that the Delegate prototype and Callback function
  // prototype are same.
 
  public delegate void CallBackDelegate(int pModule,
                                     int pEventNumber,
                                     int pEventType,
                                     int pId,
                                     double pDate1,
                                     double pDate2,
                                     int pValue,
                                     object pParams);

  /// <summary>
  /// Required designer variable.
  /// </summary>
  private System.ComponentModel.Container components = null;
  private System.Windows.Forms.Button btnCallback;

  private int mHandleModulo;

  public static CallBackDelegate myDelegate;


  public Form1()
  {
   //
   // Required for Windows Form Designer support
   //
   InitializeComponent();

   //
   // TODO: Add any constructor code after InitializeComponent call
   //
   mHandleModulo = 0;
   myDelegate = new CallBackDelegate(CallbackFunction);
   cclInitialize(null);
   mHandleModulo = cllCreateModule(null);
  }

  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   this.btnCallback = new System.Windows.Forms.Button();
   this.SuspendLayout();
   //
   // btnCallback
   //
   this.btnCallback.Location = new System.Drawing.Point(109, 125);
   this.btnCallback.Name = "btnCallback";
   this.btnCallback.TabIndex = 0;
   this.btnCallback.Text = "CallBack";
   this.btnCallback.Click += new System.EventHandler(this.btnCallback_Click);
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
   this.ClientSize = new System.Drawing.Size(292, 273);
   this.Controls.Add(this.btnCallback);
   this.MaximizeBox = false;
   this.Name = "Form1";
   this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
   this.Text = "Teste DLL ComQuest";
   this.Closing += new
System.ComponentModel.CancelEventHandler(this.Form1_Closing);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  [DllImport("MyCustomDll.dll",CallingConvention=CallingConvention.StdCall)]
  public static extern void SetCallBackPointer(CallBackDelegate Delegate);

  [DllImport("ccl.dll",CallingConvention=CallingConvention.StdCall)]
  public static extern void cclInitialize(object obj);

  [DllImport("ccl.dll",CallingConvention=CallingConvention.StdCall)]
  public static extern int cllCreateModule(object obj);

  [DllImport("ccl.dll",CallingConvention=CallingConvention.StdCall)]
  public static extern void cllSetCallBackFunction(int module, ref
CallBackDelegate cll);

  [DllImport("ccl.dll",CallingConvention=CallingConvention.StdCall)]
  public static extern void cclFreeModule(int module);

  [DllImport("ccl.dll",CallingConvention=CallingConvention.StdCall)]
  public static extern void cclFinalize();

  [DllImport("ccl.dll",CallingConvention=CallingConvention.StdCall)]
  public static extern void cclDisconnect(int module);

  private void btnCallback_Click(object sender, System.EventArgs e)
  {
   try
   {
    cllSetCallBackFunction(mHandleModulo, ref myDelegate);
   }
   catch (Exception ex)
   {
    MessageBox.Show(ex.ToString());
   }
  }

  //  Our Callback function which will be called by unmanaged code(Form
windows dll).
  public static void CallbackFunction(int pModule,
                                   int pEventNumber,
                                   int pEventType,
                                   int pId,
                                   double pDate1,
                                   double pDate2,
                                   int pValue,
                                   object pParams)
  {
   MessageBox.Show( "CallBack Function Called by Windows DLL");
  }

  private void Form1_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
  {
   cclDisconnect(mHandleModulo);
   cclFreeModule(mHandleModulo);
   cclFinalize();
  }
 }
}

a dll foi escrita em delphi:

3.3. Atribuir Endereço de Callback

Uma característica importante da DLL é o uso de ‘Callback functions’. Isso
quer dizer que o aplicativo não precisa (e não deve) ficar o tempo todo
chamando funções da DLL para perguntar se há alguma nova mensagem ou evento a
ser tratada. Ao invés disso, o aplicativo cria uma função para processar a
mensagem, passa o endereço dessa função para a DLL e a partir daí, quando
houver uma mensagem ou evento, a DLL é que vai chamar a função definida pelo
programador.

As vantagens desse sistema são:
• Menor uso de recursos de processamento
• Mais agilidade: eventos são tratados instantaneamente
• Possibilidade de se tratar assincronamente, mesmo se o aplicativo estiver
ocupado com outras atividades, como um cadastro ou a emissão de um relatório

Para isso, o programador deve definir em seu programa uma função que tenha
os parâmetros exatamente compatíveis com a função esperada, descrita abaixo

Type
TcclCallBackFunction = procedure(Module:integer; EventNumber:integer;
EventType:integer; Id:integer; Date1: double; Date2: double; Value: integer;
Params: pointer); far pascal;

Uma função compatível com a declaração acima deve estar presente no
aplicativo. Essa função é chamada pela DLL, que vai passar os parâmetros que
devem então ser tratadas pelo aplicativo.

Module: indica o handle do modulo que gerou o evento. É necessariamente o
mesmo valor retornado pela função cclCreateModule. No caso de (no futuro) um
aplicativo criar mais de um Module, esse parâmetro vai servir para
identificar de qual central o evento/mensagem veio.

EventNumber: um número seqüencial que é incrementado a cada nova mensagem. O
número é zerado sempre que a DLL é inicializada e pode ser alterado pelo
programador através da função cllSetEventNumber, descrita mais adiante.

EventType: identificador que indica de que tipo de evento/mensagem se trata.
Por exemplo, um certo valor indica que é leitura de fluxômetro, outro valor
indica que um fluxômetro foi desconectado, etc. A lista de tipos está
descrita mais adiante

Id: valor que indica o número de série do equipamento (central ou módulo de
fluxômetro, dependendo da mensagem). Em mensagens que não são específicas de
uma central, e sim, do sistema, esse valor será zero.

Date1: indica a data e hora do início do evento. No caso de uma leitura de
um fluxômetro, por exemplo, indica o início do período de leitura. Passado no
formato de data do Windows, ou seja, um número real que indica o número de
dias (incluindo a fração referente à hora atual de hoje) passados desde
31/12/1899.

Date2: indica a data e hora final do evento. No caso de uma leitura de um
fluxômetro, por exemplo, indica o final do período de leitura

Value: indica o valor da mensagem, quando aplicável. Por exemplo, no caso de
leitura de fluxômetro, considerando que ele teve 1000 pulsos entre às 16:00 e
16:10 do dia de hoje, então Date1 contém o valor referente às 16:00 do dia de
hoje, Date2 contém 16:10 e Value contém 1000.

Params: ponteiro para uma estrutura que descreve mais informações a respeito
do evento ou mensagem, nos casos em que a informação a ser passada não pode
ser resume a esses parâmetros citados anteriormente. Pode conter, por
exemplo, uma mensagem de erro ou o resultado de um auto-diagnóstico.
Reservado para uso futuro. Por enquanto deve ser ignorado.

Uma vez que o programador tenha criado a callback function, ele deve
informar à DLL o endereço da função, através da função

procedure cllSetCallBackFunction(Module:integer; Addr:Pointer); far; pascal;

Module: indica o handle do modulo de comunicação. Isso permite (mas não
obriga) que módulos diferentes chamem funções diferentes para tratar de modo
diferentes eventos vindos de centrais diferentes.

Addr: é o endereço da função de callback.


Funciona de delphi para delhi

Mas, não funciona em c# .net

Porque?

O que estou fazendo de errado?

Preciso de ajuda!

 



kdecherf
kdecherf
Added: 2:10 PM on 11/3/2005

Bad Topic ! Please post in spanish topic or speak english ^_^

Bye


Cordially,
Kdecherf
*** Do I make a mistake ? Sorry : I'm not very good ^_^ ***
theSpoke.net » English Topics » Microsoft » Objet : Callback Functions - Nada acontece preciso de ajuda!
© Copyright 2005 Microsoft Corporation. All Rights Reserved.
Terms of Use | Privacy Statement | Code of Conduct | Hosted by MaximumASP for Microsoft
WHO-BAR