2010年8月20日 星期五

[C] OOP in C sample

Because I got a job, it was a C project.
So I am learning how to implement OOP in C now.
This is a example searched form google.
I use Xcode 3.2.3 with gcc4.2 to implement and test it.


#include <stdio.h>
#include <stdlib.h>

typedef void (*Walk_Fun)(struct Animal *a_This);
typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);

typedef struct _Animal_Vtable{
Walk_Fun Walk;
Dtor_Fun Dtor;
}Animal_Vtable;

typedef struct _Animal{
Animal_Vtable vtable;

char *Name;
}Animal;

typedef struct _Dog{
Animal_Vtable vtable;

char *Name; // mirror member variables for easy access
char *Type;
}Dog;

void Animal_Walk(Animal *a_This){
printf("Animal (%s) walking\n", a_This->Name);
}

struct Animal* Animal_Dtor(struct Animal *a_This){
printf("animal::dtor\n");
return a_This;
}

Animal *Animal_Alloc(){
return (Animal*)malloc(sizeof(Animal));
}

Animal *Animal_New(Animal *a_Animal){
a_Animal->vtable.Walk = Animal_Walk;
a_Animal->vtable.Dtor = Animal_Dtor;
a_Animal->Name = "Anonymous";
return a_Animal;
}

void Animal_Free(Animal *a_This){
a_This->vtable.Dtor(a_This);

free(a_This);
}

void Dog_Walk(Dog *a_This){
printf("Dog walking %s (%s)\n", a_This->Type, a_This->Name);
}

Dog* Dog_Dtor(Dog *a_This){
// explicit call to parent destructor
Animal_Dtor((Animal*)a_This);

printf("dog::dtor\n");

return a_This;
}

Dog *Dog_Alloc(){
return (Dog*)malloc(sizeof(Dog));
}

Dog *Dog_New(Dog *a_Dog){
// explict call to parent constructor
Animal_New((Animal*)a_Dog);

a_Dog->Type = "Dog type";
a_Dog->vtable.Walk = (Walk_Fun) Dog_Walk;
a_Dog->vtable.Dtor = (Dtor_Fun) Dog_Dtor;

return a_Dog;
}


int main (int argc, const char * argv[]) {
/*
base class:
Animal *a_Animal = Animal_New(Animal_Alloc());
*/
Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());

a_Animal->vtable.Walk(a_Animal);

Animal_Free(a_Animal);

return 0;
}

2010年8月5日 星期四

[IPhone] How to make iphone automatically distinguish 640 * 960 and 320 * 640 resolution






Using two images named a.png for 480*320 and named a@2x.png for 960*480.
Then use this code.
UIImage* anImage = [UIImage imageNamed:@"a"];

[.NET] How to draw on desktop

This is a demo for draw on desktop.


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

namespace DrawDesktop
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
IntPtr hdc = GetDCEx(GetDesktopWindow(), IntPtr.Zero, 1027);
using (Graphics g = Graphics.FromHdc(hdc))
{
g.FillEllipse(Brushes.Red, 0, 0, 400, 400);
}
}

[DllImport("user32.dll")]
static extern IntPtr GetDesktopWindow();

[DllImport("user32.dll")]
static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgn, uint flags);
}
}