Here is how our client looks in Managed C++:
Listing 7. Client in Managed C++(ClientVC.cpp)
#using <mscorlib.dll> using namespace System; #using "..\Bin\CompCS.dll" #using "..\Bin\CompVC.dll" #using "..\Bin\CompVB.dll" // method "Main" is application's entry point void main() { // Iterate over component's strings and dump to console CompCS::StringComponent* myCSStringComp = new CompCS::StringComponent(); Console::WriteLine (S"Strings from C# StringComponent"); for (int index = 0; index < myCSStringComp->Count; index++) { Console::WriteLine(myCSStringComp-> GetString(index)); } // Iterate over component's strings and dump to console CompVC::StringComponent* myVCStringComp = new CompVC::StringComponent(); Console::WriteLine (S"\nStrings from VC StringComponent"); for (int index = 0; index < myVCStringComp->Count; index++) { Console::WriteLine(myVCStringComp-> GetString(index)); } // Iterate over component's strings and dump to console CompVB::StringComponent* myVBStringComp = new CompVB::StringComponent(); Console::WriteLine(S"\nStrings from VB StringComponent"); for (int index = 0; index < myVBStringComp->Count; index++) { Console::WriteLine(myVBStringComp-> GetString(index)); } }
The first thing to note is the importing of the three components, all of which are now located in the "..\Bin" relative subdirectory:
#using "..\Bin\CompCS.dll" #using "..\Bin\CompVC.dll" #using "..\Bin\CompVB.dll"
The client code that calls the three string components is identical except for specifying which library to use. The first statement in each of the three sections declares a new local variable of a type StringComponent
(defined in the component), initializes it, and calls its constructor:
CompCS::StringComponent* myCSStringComp = new CompCS::StringComponent();
After writing out a string to the Console
to say we're entering this part of the program, the client then iterates over the members – up to the value of the Count
property – of appropriate string component:
for (int index = 0; index < myCSStringComp->Count; index++) { Console::WriteLine(myCSStringComp-> GetString(index)); }
That's all that's required, and everything's repeated for the other two language components. If we had used the indexer approach rather than the separate GetString
method, the calling code would have been a more natural:
myCSStringComp[index]
Building our new C++ client is straightforward:
cl.exe /com+ ClientVC.cpp /link /entry:main /out:..\bin\ClientVC.exe
As with the previous C++ examples, we need the /com+
switch to tell the compiler to create NGWS runtime managed code. Running the resulting program yields:
C:\…\CompTest\Bin>clientvc Strings from C# StringComponent C# String 0 C# String 1 C# String 2 C# String 3 Strings from VC StringComponent VC String 0 VC String 1 VC String 2 VC String 3 Strings from VB StringComponent VB String 0 VB String 1 VB String 2 VB String 3