Showing posts with label C for Java. Show all posts
Showing posts with label C for Java. Show all posts

26 August 2011

Class methods in Java vs Objective-C

The are not the same!

Yes, although their usage is the same (singleton methods, factory methods, utility methods)

But actually class methods in ObjC is looks like instance methods. but in java they are t treated differentially than instance methods ..

Watch this example in Java (in seconds we will write it in ObjC and compare the results):


  1. 
  2. public class Abc
  3. {
  4.     public static void main(String[] args)
  5.     {
  6.         B.func();
  7.         // 1- B will inherit `func() from A.
  8.         // 2- `func()` call the method `x()`
  9.         // 3- since `func()` is a static method in Class A, it will reference non-qualified methods as static methods in the same class
 10.         // 4- `func()` will call `x()` from the same class it resids in (class A)
 11.     }
 12. }
 13. 
 14. class A
 15. {
 16.     static void x()
 17.     {
 18.         System.out.println("in A");
 19.         
 20.     }
 21.     
 22.     static void func() 
 23.     {
 24.         x(); // as if we call : A.x();
 25.     }
 26. }
 27. 
 28. class B extends A
 29. {
 30.     static void x()
 31.     {
 32.         System.out.println("in B");
 33.         
 34.     }
 35. }

Will print : in A

Now lets see how Objective C treat the same situation:


  1. //A.h
  2. #import <Foundation/Foundation.h>
  3. 
  4. @interface A : NSObject
  5. 
  6. +(void) x;
  7. +(void) func;
  8. 
  9. @end
 10. 
 11. @implementation A
 12. +(void) x
 13. {
 14.     NSLog(@"in A");
 15. }
 16. +(void) func
 17. {
 18.     [self x];
 19. }
 20. 
 21. @end


  1. //B.h
  2. #import <Foundation/Foundation.h>
  3. #import "A.h"
  4. 
  5. @interface B : A
  6. 
  7. +(void) x;
  8. 
  9. @end
 10. 
 11. @implementation B
 12. 
 13. +(void) x
 14. {
 15.     NSLog(@"in B");
 16. }
 17. 
 18. @end


  1. //Main.m
  2. #import <Foundation/Foundation.h>
  3. #import "B.h"
  4. 
  5. int main(void)
  6. {
  7. 
  8.     [B func];
  9. 
 10.     return 0;
 11. }

Will Print: in B

Conclusion:
class methods in Objective-C differ from Java.
In Java, class methods don't override each other but hide each other. Also, class methods which comes in no context (when don't being called in any other object), it calls the methods in the same class regardless whom object is calling it.
In Objective C, the existence of self keyword in the class methods make it possible to call functions based on the caller itself (self returns to the object/class that calls the function).

14 August 2011

Java Native Access (JNA) by Example..

Java Native Access is a mean by which you can call native code (C/CPP) from your java programs.

It is intend is to remove the plumbing code when using JNI..

Let's write a simple example together..

First, let's write the Native (CPP) library:
#include <iostream>

extern "C" __declspec(dllexport) 
int add (int x, int y)
{
    return x + y;
}

(Don't ask me what this line "extern "C" __declspec(dllexport)
" means, you can read in wikipedia about each term, but what you need to know, it is required to be included in our code to be able to export it to a DLL library)

Let's generate the DLL from the above source code:
g++ -c add.cc
dir add.o
g++ -shared -o add.dll add.o
dir add.dll

Now we have the file "add.dll", we need to export its contents to see whether the our "add" function is being exported or not.

There's a yet simple but powerful tool called dependencywalker
.. download it and open the dll file using it. (as shown below)

Now Let's write the Java program that will call this native function ..

You will need to download the jar file of jna library..
Download it from here.

Open Eclipse and create a new Java Project and name it as "AddJNAExample".
put the file "jna.jar" and put it in the project build path in eclipse.. and come to write the source code for the program.


package com.daz;

import com.sun.jna.Library;
import com.sun.jna.Native;

public interface Add extends Library
{
    Add INSTANCE = (Add) Native.loadLibrary("add", Add.class);
    int add(int x, int y);
}

And Here's the Driver:

package com.daz;

public class Test {
    public static void main(String[] args) {
        Add lib = Add.INSTANCE;
        System.out.println(lib.add(10, 20));
    }
}

Note, If you run it now, the following exception will be thrown:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'add': The specified module could not be found.

This is because, you will need to specify the dll library to the jvm as follows:

java -Djna.library.path="D:\dlls\add.dll" com.daz.Test

The result will be:
30

JNA involves more complex type-mappings ...

References:
http://www.cygwin.com/cygwin-ug-net/dll.html
http://today.java.net/pub/a/today/2009/05/19/protect-your-legacy-code-jna.html
http://www.dependencywalker.com/

22 July 2010

A Note about variable declaration and initialization in C vs Java

Al Salamo Alaykom,

I want to talk today about variable declarations in Java vs C.

First in Java:

We have two types of variables, method local variables and class member variables.

Class member variables (either instance or class variables):
are automatically initialized to default values which are for reference types is null and for primitive types (int, short, byte, float, double, char) is 0 (for boolean is false).
Note that, static member variables are initialized once the class get loaded by the class loader.

method local variables:
local variables in java doesn't have the concept of being static, it is always automatic variables.
It is not initialized automatically, however you cannot use it before you do the initialization yourself.
example, the following code spinet will generate compile-time error:
public static char getCh() {
char ch;
return ch; // compile error: The local variable ch may not have been initialized
}


Second in C:
In C, we have two types of variables, Global variables and local variables.

Global variables:
Global variables are automatically initialized to default values, 0 for primitives, and NULL pointer for pointers.

local variables:
C has the concept of static local variables that automatically initialized to default values once the program get executed. it uses the same defaults as global variables.

for automatic local variables, it doesn't initialized automatically, but as opposite to java, it can be used without initialization, although it will hold garbage data! although, some compilers may generate warning messages.

02 July 2010

final varaibles in Java and its relation to const in C

Hi folks,

Java uses the keyword `final` with variables in indicate that this variable is a constant.

ex1:

final int x = 10;

The above line means x is a constant of type `int` that its value cannot be altered.

ex2:
final Employee e = new Employee("Ahmed");

The above line means e is a constant of type `Employee` that its value cannot be altered.

So, the following line will not compile:
e = new Employee("Mohammed"); // compile error

But the following line will successfully compile:
e.setName("Ali");

Let's derive something:
For primitive, final is a keyword that ensure that the value of the primitive will never change.
For references, final is a keyword that ensure that the variable name cannot be reassigned to any other objects any more.

But, In C:
When we say:

//we define a pointer of type x, that its value cannot change.
int y=100;
const int* x = NULL;
*x = 20; // will not compile
x = &y; // will compile

but, when we say:

int y=100;
int* const x = malloc(sizeof(int*));
*x = 20; // will compile
x = &y; // will not compile
we define a pointer of type x, which that address its points to cannot change.

Conclusion:
So, We can say that, `final` in java with reference types act the same behavior of constant pointers in C (not value pointers). i.e. we cannot make it to refer (point) to another object, but we can change it's value.

Java never ever uses pass by reference

Hi folks,

Java never ever never uses pass by reference!

Pass by reference requires that, whenever you change the value of the reference, the value of the original object got changed.
By "change the value of the reference" I mean, use the assignment operator to do that.

Example:

class X
{
int dataMember;

X(int n)
{
dataMember = n;
}
static void m1()
{
X x = new X(10);
System.out.println("Before: " + x.dataMember);
m2(x);
System.out.println("After: " + x.dataMember);
}

static void m2(X x)
{
x = new X(30);
System.out.println("IN: " + x.dataMember);
}

public static void main(String[] args)
{
m1();
}
}
Result:

Before: 10
IN: 30
After: 10



So, In language such as C, pass by reference uses deference Pointers:


#include <stdio.h>

void wrong_pass_by_reference(int*);
void correct_pass_by_refence(int*);

int main(void)
{
int n = 0;
int *ptr = &n;

printf("Before 1: %i\n", *ptr);
wrong_pass_by_reference(ptr);
printf("After 1: %i\n", *ptr);

printf("Before 2: %i\n", *ptr);
correct_pass_by_refence(ptr);
printf("After 2: %i\n", *ptr);

return 0;
}

void wrong_pass_by_reference(int* i)
{
int x = 10;
i = &x;
printf("IN 1: %i\n", *i);
}
void correct_pass_by_refence(int* i)
{
*i = 200;
printf("IN 2: %i\n", *i);
}
Before 1: 0
IN 1: 10
After 1: 0
Before 2: 0
IN 2: 200
After 2: 200

So, Java uses an approach similar to the one used by C, but in Java you cannot deference a reference to an object, So you cannot use call by reference!

23 June 2010

a note about storage classes in C

in C programming, there are number of storage classes and which is identifiers added to the start of the variable/function definition.

we will talk about some storage classes for variables which exactly: auto, static, register and extern.

The storage class identify two important aspects, the life time of the variable (a.k.a storage duration) and the scope of the variable.

1- auto:
auto is the default for locale variables (including function parameters).
life time: created when reached, destroyed at end of the block/function in which it is defined.
scope: to the closing brace "}" of the block/function in which it is defined unless it is override by variables with the same name in inner blocks.

2- static:
static is the default for global variables.
can also applied to local variables.
It makes the variable available once it is defined to end of the program (file? I am not sure)
default value is 0 and NULL for pointers.

life time:
for global and local variables, as long as the program is running.
scope:
for global variables: the whole file.
for local variables: the whole function in which it is defined (as auto variables)

the difference between static local variable and automatic local variable is that, the local created each time it is reached, but static is still in the memory with the last value.

note: global variables cannot defined as `auto`

extern:
my info about extern is just it is used by the linker to refer to another variable defined in some other files. and it is used by global variables only.

so, global variables can be either static or extern.

register:
instruct the compiler to save this variable in CPU registers instead of memory. (only suggest, not an obligation)

summary:
the most frequently used are auto (default for local variables) and static (default for global variables).
static variables are initialized by default to zero and NULL for pointers.
static variables retain its value as long as the program is running.

24 May 2010

Casting in C vs Java

Al salamo Alykom,

I will talk about casting for primitive types in Java vs in c.

suppose we have two numbers: float f and int i:

1- the following in valid in both languages:
f = i;
2- the following is valid only in c, and will cause compilation error in java:
i = f; // in java, it should be i = (int) f;
3- promotion rules (applies in both):
int x = 10;
float d = x / 3.0f; // result is 3.333333, NOTE, the f of 3.0f only required in Java

int x = 10;
float d = x / 3; // result is 3

int x = 10;
float d = (float)x / 3; // result is 3.333333