In this activity, the C# project from 17.3 will be modified so as to again call the TimDLL.dll as developed in the Native Code chapter to get the local time.
A Compact 2013 C++ Native DLL (that builds to “TimeDLL.dll” ):
extern "C" TIMEDLL_API void GetTime( TCHAR * timeStr);
extern "C" TIMEDLL_API void GetTime(TCHAR * timeStr) { //The code as previous for getting the Local Time and creating formatted string }
extern "C" TIMEDLL_API void GetTime(TCHAR * timeStr)
{
//The code as previous for getting the Local Time and creating formatted string
}
[DllImport( “TimeDLL.dll” )] public static extern void GetTime( StringBuilder timeStr);
[DllImport( “TimeDLL.dll” )]
public static extern void GetTime( StringBuilder timeStr);
StringBuilder timeStr = new StringBuilder(..); PInvoke.GetTime(timeStr);
StringBuilder timeStr = new StringBuilder(..);
PInvoke.GetTime(timeStr);
using System; using System.Text; using System.Runtime.InteropServices; namespace ManagedTime { internal static class PInvoke { } }
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace ManagedTime
internal static class PInvoke
Add the following to the PInvoke class:
Add the following reference at the top of the app code:
Modify the TimeButton event handler to:
//Create a StringBuilder object with capacity for 100 characters StringBuilder timeStr = new StringBuilder(100); //Call the native code PInvoke.GetTime(timeStr); //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
//Display the string
textBox1.Text = timeStr.ToString( );
Build and test run the application. A runtime error will be reported that the GetTime entry point couldn't be found in the DLL. This is because C++ compiler has "mangled" the function name.
In the OS project, open the TimeDLL subproject. Modify the the GetTime function prototype in the header (.h) filer and similarly in the source (.cpp)as follows:
extern "C" TimeDLL_API void GetTime(TCHAR * strTime);
NEXT: 17.6 Calling Native Code from VB Managed Code
Click here to provide feedback and input