Title: Wednesday, 5 December 2001
1Java to C
- Wednesday, 5 December 2001
- With Donal Lafferty
- donal.lafferty_at_cs.tcd.ie
21st Session
- Contents
- Background
- Types overview
- Properties
- Interfaces
- Structs and Boxing
- Enumerations
- Classes
- Inheritance
- Polymorphism
- Fragile Base Class Problem
- Operator overloading
- Equivalence
- Conversions
3My Background
www.standonguard.com
4Blame Canada
www.standonguard.com
5C Background
- Introducing C
- Beginners
- Colleagues
- Not going to cover all of C
- Better references exist
- www.gotdotnet.com
- Essential C
- discuss.develop.com
- Contrast with Java
- Súil Eile
6Java Variable Types
- Types
- Built-ins
- Primitives
- Object
- String
- Variables
- Container
- Pass by value
- References assignable
7C Types and Variables
- Variables
- Passing
- object
- Equals
- Finalize
- ToString
- GetHashCode
8Defining Types
- Type corresponds to public operations
- class myByte
- public byte aByte
-
- Separating implementation from the type
specification - class myByteAgain
- private int aByte
- public byte getAByte() return (byte)theByte
- public void setAByte(byte value)
- theByte (int)value
-
-
- Using a programming idiom has drawbacks
- 8 tokens ? 37
- Compiler support
9Properties
- Defining C properties
- public class myByte
- private int data
- public byte Data get return (byte)data
- set data (int) value
-
- Accessing like a field
- myByte aByte new testByte()
- testByte.Data 2
- Useful?
- Flexible
- public class UART
- private byte data
- public byte BaudRate set data value
10Defining Interface Types
- Separate type and implementation
- Java simulates fields with a programming idiom
- interface myByteInterface
- byte getData()
- void setData(byte value)
-
- C simulates fields with properties
- interface IZeroByte
- byte Data get
-
11Extending and Hiding Interfaces
- Extending interfaces
- interface IByte IZeroByte
- new byte Data get set
-
- Implementing an interface implicitly
- public class myByte IZeroByte
- public byte Data get return (byte)0
-
- Implementing an interface explicitly
- interface IA
- void F()
- void F(string someArg)
-
- class A IA
-
- void IA.F() F("default") // Error!
- void IA.F(string someArg)
- Console.WriteLine("Here we go with "
someArg) -
12Implementing Multiple Interfaces
- Implementing multiple interfaces
- public class myByte_3 IByte
- private int data
- byte IByte.Data get return (byte)data
- set data (int) value
- // IByte requires that we define the
- byte IZeroByte.Data get return (byte) 0
-
- Using the results
- static void Main()
- myByte_3 ObjectReference new
myByte_3() - IZeroByte IZeroReference
ObjectReference - byte zeroValue
IZeroReference.Data - IByte IByteReference
ObjectReference - IByteReference.Data
(byte)(ZeroValue 1) - byte finalValue ObjectReference.Data //
error! -
13Type Based Operators
- as
- static void Main()
- myByte ObjectReference2 new myByte()
- // myByte does not implement IBytes
- // resulting IByteReference is a null reference
- IByte IByteReference2 ObjectReference2
as IByte -
- is
- static void Main(string args)
- myByte ObjectReference3 new myByte()
- // Manual implementation of as using is
operation - IByte IByteReference3 null
- if ( ObjectReference2 is IByte)
- IByteReference3 (IByte)ObjectReference2
-
14Basic Structs
- User-defined value type
- Definition
- public struct SimpleByte
- public byte ByteData
-
- Behaves like value-type
- SimpleByte simpleSrc
- simpleSrc.ByteData 1 // this is okay
- SimpleByte simpleDest simpleSrc
15Structs with Constructors
- Constructors semantics
- No defaults
- public struct CTORByte
- public byte ByteData
- public CTORByte (byte data)
- ByteData data
-
-
- Assignment via parameterised constructor
- Zeroed
- No access before assignment
- CTORByte CTORAssign new CTORByte(3)
16Interfaces and Efficiency with Structs
- Implementing interfaces
- sealed
- interface IDec void Dec()
- public struct BetterByte IDec
- public byte ByteData
- public void Dec () ByteData - 1
- public void Inc () ByteData 1
-
- Efficiency
- Footprint
- Allocation
- / A memory light array /
- SimpleByte smallArray new SimpleByte8
17Boxing
- Scenarios
- Collection, interfaces
- Boxing example
- BetterByte beforeBoxing
- beforeBoxing.ByteData 1
- IDec boxedByte (IDec)beforeBoxing
- boxedByte.Dec()
beforeBoxing
0
beforeBoxing
1
boxedByte
BetterByte object ByteData
IDec ref
1
18Unboxing
- Unboxing scenario
- BetterByte unboxedByte (BetterByte)boxedByte
- unboxedByte.Dec()
boxedByte
BetterByte object ByteData
IDec ref
0
19Enumerations
- Types
- enum Weekdays Sun, Mon, Tue, Wed, Thu, Fri, Sat
- enum Nibble byte Eight 8, Four 4, Two
2, - One 1, one 1
- Conversions
- Nibble myBinData (Nibble)12
- Nibble myBinData (byte)12
- byte byteData myBinData // Error!
- Values
- myBinData Nibble.Eight Nibble.Four //
Assign 12 - Java
- final static
20Inheritance
- Base class
- public class SmallByte
- public byte ByteData
- public SmallByte (byte data) ByteData data
-
- Derived class
- public class DoubleByte SmallByte
- public SmallByte SecondByte
- public DoubleByte(byte first, byte second
)base(first) - SecondByte new SmallByte(second)
- public DoubleByte(byte first) this (first,
first) -
- Demo
- DoubleByte srcByte new DoubleByte(3)
- SmallByte destByte srcByte
- DoubleByte secondSrc new DoubleByte(1,2)
- object thirdSrc secondSrc
21Polymorphism in Java
- Base class
- public class Fruit
- public String Colour() return "You tell me"
- public String Shape() return "Not sure"
-
- Derived class
- public class Orange extends Fruit
- public String Colour() return "Orange"
- public String Shape() return "Round"
-
- Use
- Fruit someFruit new Fruit()
- string a someFruit.Colour() // "You tell
me" - string b someFruit.Shape() // "Not sure"
- someFruit new Orange()
- string c someFruit.Colour() // "Orange"
- string d someFruit.Shape() // "Round"
22Static and Dynamic Binding in C
- Base class
- public class Fruit
- public string Colour() return "You tell me"
- public virtual string Shape() return "Not
sure" -
- Derived class
- public class Orange Fruit
- public new string Colour() return "Orange"
- public override string Shape() return
"Round" -
- Use
- Fruit someFruit new Fruit()
- string a someFruit.Colour() // "You tell
me" - string b someFruit.Shape() // "Not sure"
- someFruit new Orange()
- string c someFruit.Colour() // "You tell
me" - string d someFruit.Shape() // Round" lt--
Good
23Fragile Base Class
- Base class becomes dependent on derived class
Method B
Method C
Base Class
Method A
Method C '
Derived Class
24Java Example
- Base class
- public class Fruit
- public int size
- public Fruit(int size) this.size size
- public void Resize(int size)
this.ChangeSize(size) - public void ChangeSize(int size) this.size
size -
- Derived class
- public class Banana extends Fruit
- public Banana(int size) super(size)
- public void Eat() this.Resize(-1)
- public void ChangeSize(int size) this.size
size -
- Use
- Banana lunch new Banana( 10 )
- System.out.println("Size" (lunch.size)) //
Size 10 - lunch.Eat()
- System.out.println("Size" (lunch.size)) //
Size -1
25C Solution
- Base class
- public class Fruit
- public int size
- public Fruit(int size) this.size size
- public virtual void Resize(int size)
- this.ChangeSize(size)
- public virtual void ChangeSize(int
size)this.sizesize -
- Derived class
- public class Banana Fruit
- public Banana(int size) base(size)
- public virtual void Eat() this.Resize(-1)
- public virtual void ChangeSize(int size)
- this.size size
-
- Use
- Applied when variables dynamic type is or
inherits from Banana. - Banana lunch new Banana( 10 )
- Console.WriteLine( "Size0",lunch.size) //
Size10
26Pass by Reference
- ref and out
- public class IntFuncs
- static public void Zero(int data) data 0
- static public void Zero(out int data) data
0 - static public void Inc(int data) data 1
- static public void Inc(ref int data) data
1 -
- Demo
- int temp
- IntFuncs.Zero(temp) // Error! Unassigned
variable - IntFuncs.Zero(out temp) // temp set to 0
- IntFuncs.Inc(temp) // temp still 0
- IntFuncs.Inc(ref temp) // temp now 1
27Basic Operator Overloading
- Customizing and /
- public class Celsius
-
- private double temp
- public Celsius(double temp) this.temp temp
- public static Celsius operator (Celsius
LHS,Celsius RHS) - return new Celsius(LHS.temp RHS.temp)
- public static Celsius operator / (Celsius LHS,
double RHS) - return new Celsius(LHS.temp / RHS)
-
- Using overloads
- Celsius high new Celsius(15.0)
- Celsius low new Celsius(-10.0)
- Celsius average (high low)/2 // average
2.5
28Table of Operators
29Advanced Operator Overloading
- Defining as true if either temperature is
greater than 0.0 - Short-circuit evaluation
- if ( (low high) )
- return
- Becomes
- if ( low ) return 1
- else
- Celsius temp (low high)
- if (temp) return 1
-
- Relevant operators
- public static Celsius operator (Celsius LHS,
Celsius RHS) - return ( (LHS.temp gt RHS.temp) ? LHS RHS)
- public static bool operator true(Celsius c)
- return (c.temp gt 0.0)
- public static bool operator false(Celsius c)
- return (c.temp lt 0.0)
30Equivalence in C
- Comparison operators
- public static bool operator (Celsius LHS,
Celsius RHS) - return (LHS.temp RHS.temp)
-
- public static bool operator! (Celsius LHS,
Celsius RHS) - return !(LHS.temp RHS.temp)
-
- Providing a comparison for collections
- public override bool Equals(object o)
- if (o is Celsius)
- return this (Celsius)o
- return false
-
31Defining Conversions
- public class Fahrenheit
- private double temp
- public Fahrenheit(double temp)
- this.temp temp
-
- public static implicit operator
Celsius(Fahrenheit source) -
- double celsiusValue (source.temp -
32)5.0/9.0 - return new Celsius(celsiusValue)
-
-
- public static explicit operator
double(Fahrenheit source) - return source.temp
-
32Using Conversions
- Implicit conversion
- Celsius high new Celsius(15.0)
- Fahrenheit low new Fahrenheit(14)
- Celsius average (high low)/2
- Explicit conversion
- Celsius lowInCelsius new Celsius(
- ((double)low - 32.0)5.0/9.0)
33Other keywords
- const
- public const double EuroExchange 1.27
- readonly
- internal
- internal class SterlingConverter
- public readonly double Irish
- SterlingConverter( double exchange ) Irish
exchange -
- params
- string printf(string format, params object
vars) - abstract
- namespace
- namespace UCD.TCD.DSG ...
- using
- using System
342nd Session
- Contents
- Event Model
- Delegates
- Attributes
- Synchronization
- Arrays
- Pointer types
35Java Event Model
- Delegation Event Model
- Event type
- ListenerInterface
- Event Source
- Listener
- Adapter class
Source Object
Message
Message
Message
Listener
Listener Interface
Listener
Listener Interface
Listener
Listener Interface
36C Event Model
- Publisher Subscriber idiom
- Event message
- Event handler delegate
- Event publisher
- Event subscriber
Event Publisher
Event Delegate
Message
Message
Message
Subscriber
Event Handler
Subscriber
Event Handler
Subscriber
Event Handler
37Delegates
- Analogous to a C style function pointer type
- public delegate void Charge(double cash)
- Static and instance methods
- class Till
- public delegate void AddToBill(double cash)
- public void AddToReceipt(double price)
- Console.Write("Item0\n", price )
- static public void StoreTotal(double sales)
- Console.Write("Total0\n", sales )
-
- Delegate-type variables can be instantiated.
- Charge billUpdate
- Till checkout new Till()
- billUpdate new Charge(checkout.AddToReceipt)
38Delegates
- Delegates can be passed as method parameters
- static public void TestRegister(Charge update)
- update(1.27)
-
- Demo
- Charge billUpdate
- Till checkout new Till()
- billUpdate new Charge(checkout.AddToReceipt)
- TestRegister( billUpdate )
- Result
- Item1.27
39Multicast Delegates
- Void return type
- Charge billUpdate new Charge(checkout.AddToRecei
pt) - Operators to add and remove references
- // Add method reference to delegate variable
- billUpdate new Charge(Till.StoreTotal)
- billUpdate new Charge(Till.StoreTotal)
- // Make a multicast call
- billUpdate(1.27) ? checkout.AddToReceipt(1.27)
- ? Till.StoreTotal(1.27)
- ? Till.StoreTotal(1.27)
- // Remove the second method reference
- billUpdate - new Charge(Till.StoreTotal)
billUpdate checkout.AddToReciept
billUpdate checkout.AddToReciept
Till.StoreTotal Till.StoreTotal
billUpdate checkout.AddToReciept
Till.StoreTotal
40Event Message
- Example event object class
- class PushEventArgs EventArgs
- private string cause
- public string Cause get return cause
- public PushEventArgs(string cause)
- this.cause cause
-
Message
41Event Handler Delegate
- Create a delegate-type
- delegate void PushEventHandler(
- object source,
- PushEventArgs e)
Event Delegate
Event Handler
42Event Publisher
- Fire alarm
- class FireAlarm
-
- public event PushEventHandler OnPushHandler
- protected void OnPush(PushEventArgs e)
- if (OnPushHandler ! null)
- OnPushHandler(this, e)
-
- public void TestFireAlarm()
- OnPush(new PushEventArgs("Just a fire drill")
) -
43Event Subscriber
- Create listener class that implements the
call-back method - Recall the delegate type
- delegate void PushEventHandler(object source,
PushEventArgs e) - Alarm bell
- class AlarmBell
-
- public void RingBell(object source,
PushEventArgs e) -
- Console.WriteLine (e.Cause )
-
44Registering an Event Handler
- Create an event publisher
- FireAlarm publisher new FireAlarm()
- Create an event subscriber
- AlarmBell subscriber new AlarmBell()
- Create an event handler delegate
- PushEventHandler pushHandler
- pushHandlernew PushEventHandler(subscriber.RingBe
ll) - Register the event listener with the event
source. - publisher.OnPushHandler pushHandler
- Kick off a same event.
- publisher.TestFireAlarm()
45Event Modifier and Caveats
- Event modifier splits access rights
- publisher.OnPushHandler() // Error!
- publisher.OnPushHandler pushHandler// Error!
- Also
- Delegates not in CLR
- add_OnPushHandler
- remove_OnPushHandler
- Exceptions
- Property
- add / remove
- Call order
46Introducing Attributes
- Custom Attributes
- To generate custom meta-data
- Ex. MyExtraMetaInformation
- Distinguished Custom Attributes
- Passive data used by compilers or CLR
- Ex. Obsolete
- Pseudo Custom Attributes
- Analogous to pragma.
- Ex. StructLayout
47 Reserved Attributes
- Sample from C
- AttributeUsage
- StructLayout
- FieldOffset
- Obsolete
- Serializable
48Using Attributes
- Before
- public struct A_B_Struct
- public int A
- private byte b
- public byte B set b value get return
b -
- After
- Serializable, StructLayout(LayoutKind.Explicit)
- public struct A_B_Struct
- FieldOffset(0) public int A
- FieldOffset(0) private byte b
- Obsolete public byte B
- set b value get return b
-
49Equivalent Byte-code
- Serializable
- .class public explicit ansi serializable sealed
- beforefieldinit A_B_Struct
- extends mscorlibSystem.ValueType
- .pack 0
- .size 0
- // end of class A_B_Struct
- Obsolete
- .property instance unsigned int8 B()
- .custom instance void mscorlib
- System.ObsoleteAttribute.ctor() ( 01
00 00 00 ) - .set instance void AttributeStuff.A_B_Structse
t_B(unsigned int8) - .get instance unsigned int8 AttributeStuff.A_B_S
tructget_B() - // end of property A_B_StructB
- FieldOffset
- .field 0 public int32 A
- .field 0 private unsigned int8 b
50Defining a Custom Attribute
- AttributeUsage(AttributeTargets.Struct
- AttributeTargets.Property )
- public class MakerAttribute Attribute
-
- private string designer
- public string Designer get return designer
- // Constructors define the position parameters
- public MakerAttribute(string designer)
- this.designer designer
-
- // Public fields define the named parameters
- public string Programmer "None"
51Using a Custom Attribute
- Applying a custom attribute
- Maker("http//www.dsg.cs.tcd.ie/laffertd")
- public struct A_B_Struct_DL
-
- public int A
- private byte b
- Maker("http//www.dsg.cs.tcd.ie/laffertd",
- Programmer "DL")
- public byte B set b value
- get return b
-
Embedded in struct definition
Embedded in property implementation
52Accessing a Custom Attribute
- Reflective API can instantiate custom attributes
- Type type typeof(A_B_Struct_DL)
- object arr type.GetCustomAttributes(
- typeof(MakerAttribute), true)
- if (arr.Length ! 0)
- MakerAttribute maker (MakerAttribute) arr0
- Console.WriteLine(Designer 0,\nCoder
1", - maker.Designer,
- maker.Programmer)
-
- Result
- Designer http//www.dsg.cs.tcd.ie/laffertd,
- Coder None
53Quick Word on Exceptions
- Inherit from Exception
- public class StackException Exception
- public string ErrorMessage
- public StackException(string msg)
- ErrorMessage msg
-
-
- Try-Catch-Finally
- static void Main()
- try
- int a 2, b 0
- int c a/b
- catch (System.Exception problem)
- Console.WriteLine(problem.Message)
- Console.WriteLine("Happens if exception is
caught.) - finally
- Console.WriteLine("This always happens.")
54Synchronization - Locking
- Monitors provide locking
- Associated with objects
- Synchronized regions
- Demarcated by Monitor.Entry / Monitor.Exit call
pair - Monitor methods
- Hoares Monitor
- public static void Enter(object obj)
- public static void Exit(object obj)
- public static bool TryEnter(object, int)
55Synchronization Notification
- Analogous to Javas Object class methods
- public final void notify()
- public final void notifyAll()
- public final void wait()
- throws InterruptedException
- Monitor class notification operations
- public static void Wait(Object obj)
- Forces thread to sleep until monitor pulsed.
- public static void Pulse(Object obj)
- Wakes first waiting thread, does not release
monitor. - public static void PulseAll(Object obj)
- Wakes all waiting threads.
56lock Keyword
- lock defines a synchronized region
- lock( x )
- // Synchronized Region
-
- Maps to Monitor class
- System.Threading.Monitor.Enter(x)
- try
- ...
-
- finally
- System.Threading.Monitor.Exit(x)
57Thread Synchronization
- class SynchTest
- static void Main()
- SynchTest unique new SynchTest()
- Thread other new Thread(
- new ThreadStart(unique.Lockin
g)) - other.Start()
- unique.Locking()
-
- void Locking()
- for ( char c 'a' c lt'z' c )
- lock (this)
- Console.Write(c)
- Monitor.Pulse(this)
- if ( c lt 'z' ) Monitor.Wait(this)
-
-
-
- // Based on Essential C, pp108-110.
Synchronized Region
58Thread Synchronization - Equivalent
- class SynchTest
- static void Main()
- SynchTest unique new SynchTest()
- Thread other new Thread(
- new ThreadStart(unique.Lockin
g)) - other.Start()
- unique.Locking()
-
- void Locking()
- for ( char c 'a' c lt'z' c )
- Monitor.Enter(this)
- Console.Write(c)
- Monitor.Pulse(this)
- if ( c lt 'z' ) Monitor.Wait(this)
- Monitor.Exit(this)
-
-
- // Based on Essential C, pp108-110.
Synchronized Region
59Threading example
Thread1
Thread2
Thread1
Running
Blocked getting lock
Monitor.Enter(Padlock)
Monitor.Enter(Padlock)
Thread1
Running
Blocked getting lock
Monitor.Pulse(Padlock)
Monitor.Enter(Padlock)
Thread2
Suspended
Monitor.Wait(Padlock)
Running
Monitor.Enter(Padlock)
60Threading example - 2
Thread1
Thread2
Thread2
Running
Blocked getting lock
Monitor.Pulse(Padlock)
Monitor.Wait(Padlock)
Thread1
Suspended
Monitor.Wait(Padlock)
Running
Monitor.Exit(Padlock)
Thread1
Running
Monitor.Enter(Padlock)
Suspended
Monitor.Wait(Padlock)
61Threading example - 3
Thread1
Thread2
Thread1
-
- Result
- aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyy
zz
Running
Blocked getting lock
Monitor.Pulse(Padlock)
Monitor.Wait(Padlock)
Thread2
Suspended
Monitor.Wait(Padlock)
Running
Monitor.Exit(Padlock)
62Arrays
- Defining arrays
- Java can specify array type after variable or
after type - int ia
- int ia
- C always specifies array type after type
- int ia
- Initialising arrays
- Short hand for array initialization.
- int myArray 1, 2, 3, 4
- Java implicitly creates arrays of array
references - int ia 1, 2, null
- int ib new int22
- C requires explicit creation of array
references. - int ia new int2 1, 2, null
- int ib new int2, new int2
63Array Manipulation
- Implicit conversion
- class a int value
- class b a
- ...
- a aObj new b2
- foreach
- int myArray 1, 2, 3, 4
- foreach ( int Value in myArray )
- Console.WriteLine("This element contains
0",Value)
64Multidimensional Arrays
- Jagged array
- int jaggedArrayOfInts new int3
- // triangular array.
- jaggedArrayOfInts0 new int3 1, 2, 3
- jaggedArrayOfInts1 new int2 4, 5
- jaggedArrayOfInts2 new int1 6
3
2
1
5
4
6
65Multidimensional Arrays
- Rectangular arrays
- int, rectangularArray
- rectangularArray new int3,3 1,2,3,
- 4,5,6,
- 7,8,9
- int ValueofRow1Column2 rectangularArray1,2
0,
1,
2,
3
4
5
8
6
9
1
7
2
66Unsafe Code
- Unsafe context
- Declare and apply operators to pointer variables
- Convert between pointers and integral types
- Take address of variables
- Definition
- Type declarations (C Language Specification,
Section A) - public unsafe struct Node
- public int Value
- public Node Left
- public Node Right
- Members
- public struct Node
- public int Value
- public unsafe Node Left
- public unsafe Node Right
- Code blocks
67Unsafe context
- Independent from type
- public class A
- public unsafe virtual void F()
-
- public class B A
- public override void F() base.F()
-
68Pointer types
- Unmanaged types
- Built-in types
- sbyte, byte, short, ushort, int, uint, long,
ulong, char, float, double, decimal, or bool. - Any enum-type
- Any pointer-type
- Struct-type that contains fields of
unmanaged-types only - operator
- byte // Pointer to byte
- char // Pointer to char
- int // Pointer to pointer to int
- int // Array of pointers to int
- void // Pointer to unknown type
- int pi, pj // NOT as int pi, pj
- Node left // User defined struct
69Fixed vs Moveable
- Fixed
- Locals variables
- Pass by value parameters
- Pointer dereferences
- Moveable
- Array elements
- Object fields
- unsafe class Test
- static int x
- int y
- static void F(int p)
- p 1
-
70Fixed operator
- unsafe class Test
- static int x
- static string foo foo
- int y
- static void F(int p) p 1
- static void F(char p)
- for (int i 0 pi ! '\0' i)
- Console.WriteLine(pi)
-
- static void Main()
- Test t new Test()
- Int arr new int10
- fixed (int p x) F(p)
- fixed (int p t.y) F(p)
- fixed (int p arr0) F(p)
- fixed (int p arr) F(p)
- fixed (char c foo) F(c)
71Pointer Operations
- Pointer indirection ( )
- Access a member of a struct ( -gt )
- Index a pointer ( )
- Obtain the address of a variable ( )
- Increment and decrement ( / -- )
- Compare pointers ( / ! / lt / gt / lt / gt )
- Pointer arithmetic ( / - )
- Allocate memory from the call stack ( stackalloc
) - char buffer stackalloc char16
- Obtain size of unmanaged type ( sizeof )
72References
- Books
- A Programmers Introduction to C by Eric
Gunnerson, Apress - Java in a Nutshell by By David Flanagan, OReilly
- Essential C, OReilly
- JDK V1.2
- Reference Manuals
- .NET documentation
- ECMA C Specification / CLS Specification
- http//www.adtools.com/CLI
- Discussion Groups
- DOTNET on discuss.develop.com