Pages

Saturday, July 31, 2010

Publishing C/C++ code

It took me a while to figure out how to publish C/C++ code to the blog(spot). While doing so I messed up the post a few times. Finally, I got it working, and the way I wanted it, such that it looks same across the browsers and is well formatted. I tried a few things and some of them didn’t work. What didn’t work for me were plugins in Windows Live Writer (LW) to post code. Some of them didn’t show the colored text for the keywords and some didn’t have uniformity across browsers.

What worked was gvim/vim. Vim provides a command TOhtml to generate html for the code with proper syntax – exactly the way seen in vim. But that is half the job, as BlogSpot doesn’t take the html code with <head> and <body> tags of the generated html. To get it right I had to do two things. First configure vimrc to generate the desired syntax and scheme  (more on this later), and then copying the right part from the generated html. Here I will write about the way I did it using Live Writer (LW).

The published code in previous posts is inside a table, which is easy to draw in LW. So, first draw a table (1x1) in edit mode. Then in source mode copy the html generated by vim, starting from first <font> tag to the closing of it (which is at the end of the file) into that table. Even without LW this is easy to do, just add 1x1 table tags in BlogSpot edit post mode and then paste the generated html code. Explained below.

Copy the vim generated html code (as explained above) between these <td> tags.

<td valign="top" width="625"> {copy here} </td>

Note: Remove <pre> tags if any between the <td> tags.  width  can be adjusted to fit the blog.

After this add bgcolor of the <body> tag from the generated html to the <table> tag in the html code of the post. This will give the background color similar to vim scheme. At this point we have everything in place except the part, that this post won’t look same across the browsers. The reason being, first <font> tag in the pasted code. Where face is set as monospace and not a particular fixed width font, like Courier. Hence, replace whatever there is with this color="#ffffff" size="2" face="Consolas"’. This also gives the color to the ‘regular text’ in the code. In this case white (#ffffff).

This is how it will looked like on completion. Copied code marked in green.

<table border="0" cellspacing="0" cellpadding="3" width="625" bgcolor="#333333">
<tbody> <tr> <td valign="top" width="625">

<font color="#ffffff" size="2" face="Consolas, Courier New">

<Rest of the generated html code>

</font>
</td> </tr> </tbody>
</table>

Example:

1 int main(int argc, char * const argv[]) {
2     return 0;
3 }


Here is the vimrc configuration  used to get the syntax, scheme and the format. Just add these lines to the existing text. Line numbering can be turned off. If vimrc file can’t be located, typing in command - ‘e $MYVIMRC’ – will fetch it. html_use_css, is a switch to enable/disable CSS in the generated html code. The example above is without CSS styles.

set nu
colorscheme desert
syntax on
set guifont=Courier_New:h10
let html_use_css=0

 

(After writing this post, I am thinking of doing away with LW. I had hard time formatting and getting the post as I wanted.)

Thursday, July 29, 2010

C++ polymorphism

This code is to explain how polymorphism works through virtual functions and how C++ does it using VPTR and VTABLE. Please refer to my last post - C++ test code on virtual functions – to understand this better.

Code example to find out VPTR and VTABLE in C++ class. And use it to show how
polymorphism works in C++. That is same base class pointer can be used to
invoke functions of the derived class. C++ achieves this by changing the VPTR
pointer to new drived classes VTABLE.

VPTR and VTABLE usage for polymorphism in C++ Class expalined diagrammatically below. The base class object VPTR changes when base class is instantiated with that sub class, to point to the VTABLE of that sub class.

'?' - denotes VPTR will decide what subclass is currently instantiated to
the base class.

BaseClass Object
    (pobj)               SubClass_1
       |               VTABLE (vtable)
       v                     |
+------------+               v
| VPTR (vptr)|     *-->+------------+
+------------+  ?      |  VTEntry1  |------------> +------------+
| DATA1 (a)  |     *   +------------+              |  func1()   |
+------------+     |   |  VTEntry2  |--------+     |            |
| DATA2 (b)  |     |   +------------+        |     |            |
+------------+     |   |      .     |        |     +------------+
|      .     |     |   |      .     |        |
|      .     |     |   |      .     |        +---->+------------+
|      .     |     |                               |   func2()  |
|      .     |     |                               |            |
                   |                               |            |
                   |                               +------------+
                   |     SubClass_2
                   |   VTABLE (vtable)
                   |         |
                   |         v
                   +-->+------------+
                       |  VTEntry1  |------------> +------------+
                       +------------+              |  func1()   |
                       |  VTEntry2  |--------+     |            |
                       +------------+        |     |            |
                       |      .     |        |     +------------+
                       |      .     |        |
                       |      .     |        +---->+------------+
                                                   |   func2()  |
                                                   |            |
                                                   |            |
                                                   +------------+

And this is how the class hierarchy looks like in the following code.
                  +------------------+
                  |     BaseClass    |
                  +------------------+
                    /             \
                   /               \
                  /                 \
                 V                   V
+------------------+             +------------------+
|    SubClass_1    |             |    SubClass_2    |
+------------------+             +------------------+

typedef void (*func)(void); // class member function type
typedef int* ptr;           // 32 bit system pointer type

class BaseClass {
private:
    int a; // DATA1

public:
    BaseClass() : a(0) {}

    // pure virtual function
    virtual void func1() =0;
    virtual void func2() =0;
    static void deref_vtable(ptr);
};

class SubClass_1 : public BaseClass {
public:
    void func1() {
        cout << "SubClass_1::func1" << endl;
    }

    void func2() {
        cout << "SubClass_1::func2" << endl;
    }
};

class SubClass_2 : public BaseClass {
public:
    void func1() {
        cout << "SubClass_2::func1" << endl;
    }

    void func2() {
        cout << "SubClass_2::func2" << endl;
    }
};

// static function to dereference the vtable entries
void BaseClass::deref_vtable(ptr vtable) {
    func pfunc = NULL;

    // dereferencing first (VTABLE1) entry in VTABLE
    pfunc = (func)*(vtable+0);
    pfunc();

    // dereferencing second (VTABLE2) entry in VTABLE
    pfunc = (func)*(vtable+1);
    pfunc();

    return;
}

int main(int argc, char * const argv[]) {
    BaseClass *pobj = NULL;
    ptr  vptr, vtable;

    // first sub class
    pobj = new SubClass_1;
    vptr = (ptr)pobj;     // first address of obj (class) points to vptr
    vtable = (ptr)*vptr;  // dereferencing vptr to get vtable

    cout << "vptr: " << vptr << "   " << "vtable: " << vtable << endl;
    BaseClass::deref_vtable(vtable);

    delete pobj;
    cout << endl;
 
    // second sub class
    pobj = new SubClass_2;
    vptr = (ptr)pobj;     // first address of obj (class) points to vptr
    vtable = (ptr)*vptr;  // dereferencing vptr to get vtable

    cout << "vptr: " << vptr << "   " << "vtable: " << vtable << endl;
    BaseClass::deref_vtable(vtable);

    delete pobj;
    return 0;
}

Output:
vptr: 0x9934008   vtable: 0x8048cf8
SubClass_1::func1
SubClass_1::func2

vptr: 0x9934008   vtable: 0x8048ce8
SubClass_2::func1
SubClass_2::func2

polymorphtest.cpp file link

C++ virtual functions

I did this stuff while understanding virtual functions and polymorphism in C++ for job interviews. And got a chance to clean it up and comment it well (of course to be put on a blog).

This ones on virtual functions, explaining how VPTR and VTABLE work. Code is self explanatory, accompanied by a diagram.

Code example to find out VPTR and VTABLE in C++ class. And use it to probe
class virtual functions.
VPTR and VTABLE usage in C++ Class expalined diagrammatically below.

Test Class Object
     (obj)
       |             VTABLE (vtable)
       v                   |
+------------+             v
| VPTR (vptr)|------>+------------+
+------------+       |  VTEntry1  |------------> +------------+
| DATA1 (a)  |       +------------+              |  func1()   |
+------------+       |  VTEntry2  |-------+      |            |
| DATA2      |       +------------+       |      |            |
+------------+       |      .     |       |      +------------+
|      .     |       |      .     |       |
|      .     |       |      .     |       +----->+------------+
|      .     |                                   |   func2()  |
|      .     |                                   |            |
                                                 |            |
                                                 +------------+

typedef void (*func)(void); // class member function type
typedef int* ptr;           // 32 bit system pointer type

class Test {
public:
    int a; // DATA1

    Test() : a(0) {}

    virtual void func1() {
        cout << "Test::func1" << endl;
    }

    virtual void func2() {
        cout << "Test::func2" << endl;
    }
};

int main(int argc, char * const argv[]) {
    Test obj;
    int  *pdata;
    ptr  vptr, vtable;
    func pfunc = NULL;

    vptr = (ptr)&obj;     // first address of obj (class) points to vptr
    vtable = (ptr)*vptr;  // dereferencing vptr to get vtable
    pdata = (int*)((ptr)&obj+1); // this is 'a', the first member of class Test

    *pdata = 10;
    cout << "pdata (a): " << *pdata << endl;
    cout << "vptr: " << vptr << "   " << "vtable: " << vtable << endl;

    // dereferencing first (VTEntry1) entry in VTABLE
    pfunc = (func)*(vtable+0);
    pfunc();

    // dereferencing second (VTEntry2) entry in VTABLE
    pfunc = (func)*(vtable+1);
    pfunc();

    return 0;
}

Output:
pdata (a): 10
vptr: 0xbfee67d4   vtable: 0x8048a80
Test::func1
Test::func2

virtualtest.cpp file link