This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Monday, 18 March 2013

What Is Callback Functions in C


 Callback Functions Tutorial.
 


Introduction:

If you are reading this article, you probably wonder what callback functions are. This article explains what callback functions are, what are they good for, why you should use them, and so forth? However, before learning what callback functions are, you must be familiar with function pointers. If you aren't, consult a C/C++ book or consider reading the following.



 What Is a Callback Function?
 


The simple answer to this first question is that a callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function to an argument to another, when that pointer is used to call the function, it points to it is said that a callback is made.


 Why Should You Use Callback Functions?
 


Because they uncouple the caller from the callee. The caller doesn't care who the callee is; all it knows is that there is a callee with a certain prototype and probably some restriction (for instance, the returned value can be int, but certain values have certain meanings)if you are wondering how is that useful in practice, imagine that you want to write a library that provides implementation for sorting algorithms (yes, that is pretty classic), such as bubble sort, shell short, shake sort, quick sort, and others. The catch is that you don't want to embed the sorting logic (which of two elements goes first in an array) into your functions, making your library more general to use. You want the client to be responsible for that kind of logic. Or, you want it to be used in various data types (ints, floats, strings, and so on). So, how do you do it? You use function pointers and make a callback.

A callback can be used for notifications. For instance, you need to set a timer in your application. Each time the timer expires, your application must be notified. However, the implementer of the timer's mechanism doesn't know anything about your application. It only wants a pointer to a function with a given prototype, and in using that pointer it makes a callback, notifying your application about the event that has occurred. Indeed, the SetTimer() WinAPI uses a callback function to notify that the timer has expired (and in case there is no callback function provided. It posts a message to the application's queue).

Another example from WinAPI functions that use callback mechanism is EnumWindow(), which enumerates all the top-level windows around the screen. Enum Window() iterates over the top-level windows, calling an application-provided function for each window, passing the handler of the window. If the callee returns a value, the iteration continues; otherwise, it stops. EnumWindows() just doesn't care where the callee is and what it does with the handler it passes over. It is only interested in the return value, because based on that it continues its execution or not.

However, callback functions are inherited from C. Thus. In C++, they should be only used for interfacing C code and existing callback interfaces. Except for these situations, you should use virtual methods or function, not callback functions.



 A Simple Implementation Example
 

Now, follow the example that can be found in the attached files. I have created a dynamic linked library called sort.dll. It exports a type called CompareFunction:



 typedef int (__stdcall *CompareFunction)(const byte*, const byte*);


Which will be the type of your callback functions. It also exports two methods, called Bubblesort() and Quicksort(), which have the same prototype but provide different behavior by implementing the sorting algorithms with the same name.



    void DLLDIR __stdcall Bubblesort(byte* array,
    int size,
    int elem_size,
    CompareFunction cmpFunc);



    void DLLDIR __stdcall Quicksort(byte* array,
    int size,
    int elem_size,
    CompareFunction cmpFunc);
   
 
These two functions take the following parameters:

    Byte* array: a pointer to an array of elements (doesn't matter of which type)

    int size: the number of elements in the array

    int the elem_ size: the size, in bytes, of an element from the array

    CompareFunction cmpFunc: a pointer as a callback function of the prototype listed above.

The implementation of these two functions performs a sorting of the array. However, each time there is a need to decide which of two elements goes first, a callback is made about the function whose address was passed in an argument. For the library writer, it doesn't matter where that function is implemented, or how it is implemented. All that matters it is that it takes the address of two elements (that are the two be compared), and it returns one of the following values (this is a contract between the library developers and its clients):

    -1: if the first element is lesser and/or should go before the second element (in a sorted array)

    0: if the two elements are equal and/or their relative position doesn't matter (each one can go before the other in a sorted array)

    1: if the first element is greater and/or should go after the second element (in a sorted array)

With this contract explicitly stated, the implementation of the Bubblesort() function is this (for Quicksort(), which a bit more complicated, see the attached files).


 void DLLDIR __stdcall Bubblesort(byte* array,
    int size,
    int elem_size,
    CompareFunction cmpFunc)
    {
    for(int i=0; i < size; i++)
    {
    for(int j=0; j < size-1; j++)
    {
    // make the callback to the comparison function
    if(1 == (*cmpFunc)(array+j*elem_size,
    array+(j+1)*elem_size))
    {
    // the two compared elements must be interchanged
    byte* temp = new byte[elem_size];
    memcpy(temp, array+j*elem_size, elem_size);
    memcpy(array+j*elem_size,
    array+(j+1)*elem_size,
    elem_size);
    memcpy(array+(j+1)*elem_size, temp, elem_size);
    delete [] temp;
    }
    }
    }
    }


      Note: Because the implementation uses memcpy(), these library functions should not be used for types other than POD (Plain-Old-Data).On the client side, there must be a callback function whose address is to be passed to the Bubblesort() function. As a simple example, I have written a function that compares two integer values and one that compare two strings:



   int __stdcall CompareInts(const byte* velem1, const byte* velem2)
    {
    int elem1 = *(int*)velem1;
    int elem2 = *(int*)velem2;
    
    if(elem1 < elem2)
    return -1;
    if(elem1 > elem2)
    return 1;
    
    return 0;
    }
    
    int __stdcall CompareStrings(const byte* velem1, const byte* velem2)
    {
    const char* elem1 = (char*)velem1;
    const char* elem2 = (char*)velem2;
    
    return strcmp(elem1, elem2);
    }


 

To put all these to a test, I have written this short program. It passes an array of five elements to Bubblesort() or Quicksort() along with the pointer to the callback functions.


   int main(int argc, char* argv[])
    {
    int i;
    int array[] = {5432, 4321, 3210, 2109, 1098};
    
    cout << "Before sorting ints with Bubblesort\n";
    for(i=0; i < 5; i++)
    cout << array[i] << '\n';
    
    Bubblesort((byte*)array, 5, sizeof(array[0]), &CompareInts);
    
    cout << "After the sorting\n";
    for(i=0; i < 5; i++)
    cout << array[i] << '\n';
    
    const char str[5][10] = {"estella",
    "danielle",
    "crissy",
    "bo",
    "angie"};
    
    cout << "Before sorting strings with Quicksort\n";
    for(i=0; i < 5; i++)
    cout << str[i] << '\n';
    
    Quicksort((byte*)str, 5, 10, &CompareStrings);
    
    cout << "After the sorting\n";
    for(i=0; i < 5; i++)
    cout << str[i] << '\n';
    
    return 0;
    }

 

If I decide that I want the sorting to be done descending (with the biggest element first), all I have to do is to change the callback function code, or provide another that implements the desired logic.

Calling Conventions.

In the above code, you can see the word __stdcall in the function's prototype. Because it starts with a double underscore, it is, of course, a compiler-specific extension, more exactly a Microsoft-specific one. Any compiler who supports the development of Win32-based applications must support this or an equivalent one. A function that is marked with __stdcall uses the standard calling convention so named because all.

Win32 API functions (except the few that take variable arguments) use it. Functions that follow the standard calling convention remove the parameters from the stack before they return to the caller. This is the standard convention for Pascal. However, in C/C++, the calling convention is that the caller cleans up the stack instead of the called function. To enforce that a function uses the C/C++ calling convention, __cdecl must be used. Variable argument functions use the C/C++ calling convention.

Windows adopted the standard calling convention (Pascal convention) because it reduces the size of the code. This was very important in the early days of Windows, when it ran on systems with 640 KB RAM.

If you don't like the word __stdcall, you can use the CALLBACK macro, defined in windef.h, as.

  #define CALLBACK __stdcall

                   

  OR

     #define CALLBACK PASCAL

Where PASCAL is #defined as __stdcall.

Sunday, 17 March 2013

Write a Program to Swap Two Numbers Without Using Third Variable

Program to swap two numbers without using Third Variable. Here we are using two variables of into the type.


#include<stdio.h>

int main()

{

              int a=10,b=20;

              Printf(“without swapping %d %d”,a,b);

              a=^b;

               b=^a;

               a=^b;

              printf(“after swapping %d %d”,a,b);

              getch();

}





Output:-a=20,b=10





What Is Structure Padding


Structure padding is done to do memory alignment. As size of Pointer is 4 bytes, If everything is organized by multiple of 4 that it will be easier and faster to calculate the address and processing them. Structures are used to club different size variable. Compiler will align to 4 bytes boundaries and for that it needs padding structure padding is done by the compiler,  and this depends on the some architecture  cannot access the date which will be stored on the odd address, or they may find difficult to access  if this is the reason for padding extra bytes.

Padding will be done by the compiler to structure members and to  be a structure  as a whole also. Compiler padding structure as whole because this allows each member of structure aligned in the array of structure.

  Structure padding example:




 Struct
  {
          char a;   //1 byte
          int b;    //2 byte
          char c;    //1 byte
          long int d;   //4 byte
}

 

Due to structure padding the structure size is 12 bytes

Friday, 15 March 2013

What Is Dangling Pointer

A pointer pointing to a dead location than it is called dangling pointer. When ever a function returning an integer than specified return type as int. Whenever a function returning an address of integer then specified return type as int(function returns an address).

Example:



   #include<stdio.h>
               
               float *call();

               void main()

               {

                         float *ptr;

                         ptr=call();

                        clrscr();

                        printf("%d",*ptr);

               }

             float * call()

             {

                  float z=2.5;

                  ++z;

                  return &z;

             }

           


 Output: Randam value



Explanation: variable z is local variable. Its scope and lifetime are within the function call hence after returning the address of z variable z became dead and pointer is still pointing ptr is still pointing to that location.




 Solution of this problem: Make the variable z is as a static variable.

Thursday, 14 March 2013

What Is Watchdog?

when micro controller hang up or gets crashed.To overcome these situation is to automatically reset the system.

Whenever Such a Situation Arises:-

The watchdog is a hardware or software generated timer interrupt which resets the system in the situation when system huge up . The watchdog timers are also used in case when you intentionally required the system without any physical interference.Watchdog is a special timer which can be enabled in any section of the code and when enable it ensurers that a certain number of instructions execute within a per-defined time frame.


Watch Dog Timer Control Register are:-

WDTOE( watch dog turn-off enable).

The watchdog timer is disabled by configuring WDTOE and WDE bits.

WDE(watch dog enable) -watchdog timer is enabled by writing 1 to WDE bit.

WDP(watch  dog prescal ) bits.

These three bits determine the watchdog time out condition.

Watchdog Timer Works:-

The watchdog timer starts when the WDE bit is enable and pres-cal bits are configured for time-out conditions.As watchdog timer reaches time-out condition, watchdog timer is reset and generate a pulse of one clock.Cycle with reset the program counter. when Watchdog timer resets the timer , the WDRF (watch dog reset Flag) bit in micro-controller register is set by the hardware to disable the watchdog timer.

1. Set the WDE and WDTOE bits in same clock cycle WDTCR register. The logic one must be written to WDE bit even though it is set to one already.

2. After four clock pulses. write logic 0 to the WDE bit. otherwise watchdog timer will not be Disable.

Wednesday, 13 March 2013

What Is Near Pointer?

The Pointer which can point only 64KB data segment or segment number 8 is known as near Pointer. That is near pointer cannot access beyond the data segment like graphics video memory, text video memory, etc. Size of near pointer is two bytes. With help keyword near, we can make any pointer as near Pointer.

Examples:


   #include<stdio.h>

          int main()
{

         int x=25;

         int near* ptr;

          ptr=&x;

         printf(“%d”,sizeof ptr);

         return 0;
}



Output: 2

(2)



#include<stdio.h>

int main()
{

  int near* near * ptr;

  printf(“%d”,sizeof(ptr),sizeof(*ptr));

  return 0;

}




 Output: 2 2


Explanation: Size of any type of near pointer is two bytes. Near pointer only hold 16 bit offset address. Offset address varies from 0000 to FFFF (in hexadecimal). In printf statement to print the offset address in hexadecimal, %p is used.
Example:


#include<stdio.h>

int main()
{

     int i=10;

     int *ptr=&i;

    printf("%p",ptr);

    return 0;

}




 Output: Offset address in the hexadecimal number format.

%p is also used to print any number in the hexadecimal number format.

Example:




#include<stdio.h>

int main()
{

   int a=12;

  printf("%p",a);

  return 0;

}




 Output: 000C

Explanation: Hexadecimal value of 12 is C.

Consider the following two c program and analyze its output:

(1)



#include<stdio.h>

int main()
{

     int near * ptr=( int *)0XFFFF;

     ptr++;

     ptr++;

    printf(“%p”,ptr);

   return 0;

}




Output: 0003


(2)



#include<stdio.h>

int main()
{

      int i;

      char near *ptr=(char *)0xFFFA;

      for(i=0;i<=10;i++){

      printf("%p \n",ptr);

      ptr++;

}

return 0;

}




Output:

FFFA   FFFB  FFFC  FFFD  FFFE   FFFF

0000    0001    0002    0003    0004


Explanation: When we  increment or decrement the offset address from maximum and minimum value respectively then it repeats the same value in cyclic order. This property is known as cyclic nature of offset address. Cyclic property of offset address. If you increment the near pointer variable, then moves clockwise direction If you decrement the near pointer, then moves anti clockwise direction


What is the default type of pointer in C?

Answer: It depends upon the memory model.

What Is Function Pointer


Function Pointer is a variable(a pointer) that holds the address  of another function. Function pointer is a pointer variable, just like a normal pointer. However, function pointer points to the address of the function. In C like all normal variables, functions also will be stored in the memory. So every function will have a valid address. Function pointer will point to this address.


Syntax:



DATA TYPE (*ptr) ();
DATA TYPE (*ptr) (Data Type);


When declaring a function pointer you must declaration the function's return type and the function's parameter type. Example supposes we had two functions.


Void read_emp (emp*e);
  and
Void print_emp(emp*e);


We can declare a variable that could pointer to either of these functions as follows:


void(*func_ptr) (emp*e);


(*func_ptr)  Is the name to the variable, void' is actual variable declaration void(*func-ptr) (emp*e); ,(*func-ptr)  is variable declaration, void * func-ptr(emp*e);


 Upper syntax it will return a void pointer


 (void * func-ptr(emp*e); is the function prototype)

Suppose  you to have third function;

Void print_integer (int x);

It would not be possible to assign func_ptr to pointer to print_integer as they are  different  function types   parameter is  different types.Using the example for the previous.

void(*func_ptr) (emp*e);,we could assign func_ptr to pointer to read_emp as follows,

 Func_ptr=read_emp,note that no  &  is required, note (extremely important) that,Func_ptrr=ead_emp is very different from,Func_ptr=read_emp();

(Func_ptr=read_emp; take  the function  pointer an address and assign to func_ptr variable)

(Func_ptr=read_emp(); is read_emp() run the program and return value is assigned  to func_ptr).Once func_ptr has been initialized.

Func_ptr=read_emp;


We can call the function read_emp via func_ptr, as follows.


  emp e;


 Func_ptr(&e);



  Example



 static int add(int a,int b)
               {
                           return a+b;
                }



 static int sub(int x,int y)
             {
                         return a-b;
             }



   main()
              
         {

                    int x,y;

                    int temp;

                    int result;

                    int(*func_ptr) (int,int);   // function pointer

                    printf("please enter the first number");

                   scanf("%d",&x);

                    printf("please enter the second number");

                   scanf("%d",&y);

                   printf("you want to Add or Subb y/n");

                  scanf("%c",temp);

                  if(temp=='y')||(get char()=='a')

                  func_ptr=int add; // pointing to function

                  else

                  func_ptr=int subb; // pointing to function

                 return=func_ptr(x,y);

                 printf("%d\n",result);

}


Example 2




int fun ptr()

{
            static int s=10;
              ++s;
             Returns;
}


void main()
{
       int r;

       int(*ptr) ();  // function pointer

       ptr=funptr;

      r=ptr();   //r=funptr();    //r=funptr()

      printf("\n valu=%d",r);

}

Twitter Delicious Facebook Digg Stumbleupon Favorites More