c#의 콜백함수란?

|
using System;
using System.Runtime.InteropServices;

public delegate bool CallBack(int hwnd, int lParam);

public class EnumReportApp
{
    [DllImport("user32")]
    public static extern int EnumWindows(CallBack x, int y); 

    public static void Main() 
    {
        CallBack myCallBack = new CallBack(EnumReportApp.Report);
        EnumWindows(myCallBack, 0);
    }

    public static bool Report(int hwnd, int lParam)
    { 
        Console.Write("Window handle is ");
        Console.WriteLine(hwnd);
        return true;
    }
}


example 0)
void (*p_func)(char *) = NULL;
extern void my_print(char *s);
void test(char *s)
{
    p_func = my_print;
    p_func(s):

}

example 1)

float Plus    (float a, float b) { return a+b; }
float Minus   (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide  (float a, float b) { return a/b; }

float Calculate(float a, float b, float (*p_Function)(float, float))
{
   float result = p_Function(a, b);
   return result;
}

int main(void)
{
    Calculate(10, 20, &Plus);
    return 0;
}


example 2)
typedef struct
{
  void(*callback_fn)(void);
}
 test_callback_t;

extern void test1();
extern void test2()

void test(void)
{
  test_callback_t callback[2];
  /*원래는 함수이름 앞에 &를 붙이는 것이 더 정확하고 이식성이 좋다*/
  callback[0].callback_fn = test1;
  callback[1].callback_fn = test2;
  /*Call callbacks*/

  callback[0].callback_fn();
  callback[1].callback_fn();

  return;
}





콜백은 함수를 직접 호출하지 않고 다른 함수가 대신 호출하게 하는 것입니다.


 typedef struct 
    {
        int number;
        const char* name;
    } S;

    int cmp_by_number(const void* p1, const void* p2)
    {
        const S* ps1 = p1;
        const S* ps2 = p2;
        return ps1->number - ps->number;
    }

    int cmp_by_name(const void* p1, const void* p2)
    {
        const S* ps1 = p1;
        const S* ps2 = p2;
        return strcmp(ps1->name, ps2->name);
    }

    S array[10];
    qsort(array, 10, sizeof(S), cmp_by_number); // number 순으로 정렬
    qsort(array, 10, sizeof(S), cmp_by_name);   // name 순으로 정렬

qsort 입장에서는 주어진 데이터를 어떻게 정렬할지 미리 알 수는 없으므로
qsort를 호출하는 쪽에서 "이런 방법으로 정렬하라"는 정보를 콜백을 통해
알려주는 것입니다.



이것도 콜백의 일종이라고 볼 수 있겠지요. 만약 call_back_func_1,... 등이
여러 개 있고 test_func에서 호출할 함수를 미리 결정할 수 없다면 함수포인터를
이용한 콜백이 좋은 방법입니다. 예를 들어
void call_back_func_1(int a);
void call_back_func_2(int a);

int answer;
switch (answer)
{
case 1:
     test_func(call_back_func_1, answer);
     break;
case 2:
     test_func(call_back_func_2, answer);
     break;
}







http://msdn.microsoft.com/ko-kr/library/ms173171.aspx




Trackback 0 And Comment 0