Calling a Web Service from Unmanaged C

Calling a Web Service from Unmanaged C++

If you need to write a new application that uses a Web Service, you will probably write it in managed C++. But what if you have an existing unmanaged C++ application, and you want to enhance it to use a Web Service?

Create a Win32 console application called UnManUseUtilities . Add a Web reference to the Utilities project using the same URL to the .asmx file as before, http://localhost/Utilities/Utilities.asmx .

Edit UnManUseUtilities.cpp so that it reads as follows :

 
 // UnManUseUtilities.cpp : Defines the entry point for the console application. // #include "stdafx.h"  #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) {     ::CoInitialize(NULL);     { //brace brackets for scope only     UtilitiesClass::CUtilitiesClass ws;     int i = 3;     double d = 1.5;     bool result;     ws.Factor(i,d,&result);     if (result)         cout << "1.5 is a factor of 3"  << endl;     else         cout << "1.5 is not a factor of 3"  << endl;     i = 4;     d = 1.7;     ws.Factor(i,d,&result);     if (result)         cout << "1.7 is a factor of 4"  << endl;     else         cout << "1.7 is not a factor of 4"  << endl;     } // forces destruction of ws     ::CoUninitialize();     return 0; } 

This code starts and ends with a call to CoInitialize() and CoUninitialize() , because access to Web Services from unmanaged C++ is offered through COM. The proxy object that is created by this code must be cleaned up before CoUninitialize() is called, so there is a set of brace brackets here just to establish that scope and trigger the destruction of the proxy object.

Inside the brackets, this code creates the proxy object and calls its Factor() method. Notice that even though this is the very same managed Web method that was called from managed code earlier in this chapter, the signature of this unmanaged proxy is different from the signature of the managed proxyit takes three parameters, and the third is passed by address so the function can change it. This code is not as simple to write or maintain as the managed code equivalent, so unmanaged code should probably not be your first choice, but it's by no means impossibly hard for you to use a Web Service from unmanaged code.



Microsoft Visual C++. NET 2003 Kick Start
Microsoft Visual C++ .NET 2003 Kick Start
ISBN: 0672326000
EAN: 2147483647
Year: 2002
Pages: 141
Authors: Kate Gregory

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net