Filip Ekberg's blog

November 30, 2009

Function pointers in C and Python and their possible usage

Filed under: Architecture, Programming, Python, c-programming — Tags: , — Filip Ekberg @ 4:07 pm

Function pointers? you might ask yourself, well this little trick gets handy sometimes, I will provide an example of a practical use in a later post on the next euler solution. Might actually do it in C too just to prove that C is still neat.

So to kick this off, what are function pointers? Well for those deep down the rabbit hole ( .NET guys that is ), might not really have a clue on the matter, and others might dissaggree and now exactly what it is. So just to keep the air clear here, function pointers are “pointers” that direct you to a function, easy huh?

Well, you probably got as much from just reading the phrase but, it’s not really rocket science. If you are familiar with references or reference types, such as Strings and Objects, you know that there are different types of memory in which your program operates. When you create an Object you store your data on a shared memory place. There are shared memory and program reserved memory ( the stack! ). So you might want to look at this as a “reference” to a function.

So when would this be nessecary? Imagine the scenario where you might want to performe some calculation but you don’t know what type of API the end user which will end up using your API have. Let’s say that the method “square” ( x^x ) would not be defined. So you might end up having to use function pointers, where you ask the user to suppy the function for calculating square of x.

In Python the Square function for x^x will look like this

1
2
3
4
5
6
def square(i):
        result = i;
        for x in range(i-1):
                result *= i

        return result

In C it will look like this

1
2
3
4
5
6
7
8
9
10
11
12
int square(int i)
{
        int result = i;
        int x = 1;

        for ( x = 1; x < i; x++ )
        {
                result *= i;
        }

        return result;
}

Now these two look fairly similar don’t they? Well sure, the only real difference is the dialekt right? It’s just programming. So let’s get to the cool parts. In python, we would solve this problem easy, since it’s not a strongly typed language everything could be a function, right. So let’s check the decleration for calculate.

But before we check that out, let’s just make it clear that our Usage will be somewhat like, give me a function that calculates square of a+b, this means, the result should be (a+b)^(a+b).

So this is the function decleration in Python

1
def calculate(func, a, b)

Not that hard, right? Well, keep in mind that Python is a “modern” language, it’s more of a scripting language.

Check this out and notice the fairly big difference

1
int calculate(int (*func)(int c), int a, int b)

If you are not familiar with pointers I would suggest you dig down the archive on my blog and check out the chapters about that. So what this really does in C is that you tell the compiler that, okay this function takes a pointer to something that will look like this, and you write the declaration of the function again. So, in this case you really need to know what it looks like. With standard parameter values in Python you could acheive some really cool things without knowing the decleration of the function.

Now we’ve seen how to Create the methods, taking arguments that are functions, how about using them inside your code?

Check this C example of the whole Calculate function

1
2
3
4
int calculate(int (*func)(int c), int a, int b)
{
        return (*func)(a+b);
}

And in Python the following will look like this

1
2
def calculate(func, a, b):
        return func(a+b);

There is a notable difference here, but I can honestly say that I like the C-style.

Try out the python version!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/python

def square(i):
        result = i;
        for x in range(i-1):
                result *= i

        return result

def calculate(func, a, b):
        return func(a+b);

def main():
        print calculate(square, 1, 1)

if __name__ == "__main__":
    main()

Happy Coding!

August 22, 2008

Importance of good Architecture, Structure and Patterns

Filed under: Architecture — Tags: — Filip Ekberg @ 9:54 pm

Often when developing software such as websites, windows ( or any other operative system for that matter ) programs, the begining of the progress is quite simple; you have your ideas and may have some thoughts about how to implement everything. But what often is forgot when developing software is the importance of thinking ahead, thus, planning for a larger software that you have in mind.

For an example, when i started developing SmartIT Invoice i thought of it as a software that would generally help me organize my small amount of invoices. But as the years pass my company grows bigger and bigger and once im up to n-numbers of invoices, a simple List View won’t be sufficient. Therefore after implementing my Invoice software, i started thinking about how i could change everything and structure the code for helping me in the future. I had in mind that i might not always want to use the Windows Graphical Interface for input and output so as i always do, i seperate the Design code from the Logical Code. This meaning that my application has three layers. Them being:

  • Application Layer, code for display, handling window events
  • Logic data layer, database connections, objects
  • Data layer, this being the database with functions, views and procedures

By having these three layers i can easily change one of the layers without changing the next. Of course this is not entierly true, i would have to change some parts in the Logic Data Layer if i changed the DBMS.  I would however not have to change that much if i just changed the behaviour of a Stored procedure.

Again takng my Invoice softwre as an example, i recently released a software called Webexpress.nu which allows customers to create their own website and for this i need somewhat of a payment system. Of course using Credit card payments is nice and easy but not entierly nessesary. So by just adapting my Webste to the current Logic Data Layer of my SmartIT Invoice software, i could easily get an intergration that allowed me to create customer invoices that pops up on the user account, when they are online on the page of course and even directly to my software, withouth any adjustments in the Data Layer or in my Windows Software.

This proves the point that well structured code and seperate layers will help you along the way of program development.

As a side note the Data Layer in this case is a Windows DLL with .NET 3.5 code which makes it even easier to implement when the website itself is asp.net with .net 3.5.

There are a lot of good design guidelines out there which will help you structure your software better and help you understand how to always follow a pattern. A pattern doesn’t, in my point of view, have to be a pattern like Singelton etc, it can by any means be a way for yourself to regocnize your own code, thus following a pattern. Example, i often tend to use m_ before member variables and write all functions and access methods with a capital letter.

Have fun programming!

August 8, 2008

Objects, Objects, Objects!

Filed under: Architecture, Programming — Tags: , — Filip Ekberg @ 9:55 pm

By looking on everything in life as Objects is one of the benefits from doing object oriented programming. It doesn’t really matter if you master the technique or if you are in the beginners stage, just starting with object oriented programming will open up your eyes.

Seeing how objects change your perspective on both programming and other stuff in life, i’ve notied that when i wanted to learn something like animating in Flash, knowing object orientation helps. Not particulary with the animating, but with the thoughts on how i will structure my animations.

I.e. that i have to create a move, where a part in this move occures many times, repeatinly creating this scenes and moving them around is a fairly harsh work. Looking at it from an object oriented perspective you see that you have:
A main film
An object containging the scene

When needed, you just insert a new object of the scene and you never need to repeate the procedure of creating the scene.

Using Objects isn’t always good though, when you need to store the memory on other medias than the RAM you need it to be serialized, which is not handled to good by some languages such as PHP.

The basics of object orientation is easy to learn over a few minutes, when you try to look at everthing at a new perspective, the learning period will decrease.

Let’s say that you have a Car, this car has 4 wheels, 5 doors, 6 windows and so on. The doors got handles, the wheels got air in them and so on. Seeing all these parts as Objects is a good way to play with the thoughts of object orientation. See how i apply inheritage on a car:

1
2
3
4
5
6
7
8
9
10
abstract class BasePart
{
    int m_ModelNr;
    string m_Name;
    public BasePart(int ModelNumber, string Name)
    { 
         m_ModelNr = ModelNumber;
         m_Name = Name;
    }
}

Everytime you create something, the created part / object or wathever got a Model Number and a Name, just look at carparts or a coka cola bottle.

1
2
3
4
5
6
7
8
9
10
11
class Door : BasePart
{
    int m_DoorType;
    int m_Weight;
    int m_Code;

    public Door(int DoorType, int Weight, int Code, int ModelNumber, int Name) : base(ModelNumber, Name)
    {
     ///.....
    }
}

The codesnippet above shows the basics in object orientation, this is a Base Class which is Abstract, which means that you cannot create an object of it.
The Door is derived from a BasePart because its a BasePart.

Powered by WordPress