Managed Code C# DLL
In this activity the local time string will be generated in a managed code DLL rather than pinvoked from a native code DLL. This is implemented by using a static class as per the PInvoke one in 17.5 and 17.6 but implements the actual local time string generation within the class. The class is compiled in a separate project into a standalone DLL. The class will be coded in C# but could just as easily be coded in Visual Basic.
Note: The PInvoke class could also be similarly compiled into a DLL to simplify it reuse with other applications.
Initially the application from 17.5 will be used. The only change to it will be to change the name of the class being called by it. The 17.6 app will also be used to demonstrate cross-language debugging.
using System; using System.Text; namespace ManagedTime { public static class Time { } }
using System;
using System.Text;
namespace ManagedTime
{
public static class Time
}
public static void GetTime( StringBuilder dateTime) { //Get local time DateTime localTime = DateTime.Now; // Generate formated string string dateTimeStr = string.Format( "Time {0}:{1}:{2} Date {3:2}//{4:2}//{5:4}", localTime.Hour, localTime.Minute, localTime.Second, localTime.Day, localTime.Month, localTime.Year); //Assumes that dateTime has allocated space dateTime.Insert(0, dateTimeStr); }
public static void GetTime( StringBuilder dateTime)
//Get local time
DateTime localTime = DateTime.Now;
// Generate formated string
string dateTimeStr = string.Format(
"Time {0}:{1}:{2} Date {3:2}//{4:2}//{5:4}",
localTime.Hour, localTime.Minute, localTime.Second,
localTime.Day, localTime.Month, localTime.Year);
//Assumes that dateTime has allocated space
dateTime.Insert(0, dateTimeStr);
//Create a StringBuilder object with capacity for 100 characters StringBuilder timeStr = new StringBuilder(100); //Call the native code Time.GetTime(timeStr); //<—Change this //Display the string textBox1.Text = timeStr.ToString( );
//Create a StringBuilder object with capacity for 100 characters
StringBuilder timeStr = new StringBuilder(100);
//Call the native code
Time.GetTime(timeStr); //<—Change this
//Display the string
textBox1.Text = timeStr.ToString( );
NEXT: 17.8 Managed Code Callbacks
Click here to provide feedback and input