Home > Articles > Programming > Windows Programming

Interacting with Visual Basic and C# Components

  • Print
  • + Share This
Microsoft has proclaimed the ease and capability of interacting with objects created in other languages as the benefits of the .NET platform and the CLR. Just how easy and effortless is it to interact with objects created in other languages? That's what Davis Chapman explores in this excerpt from Sams Teach Yourself Visual C++ .NET in 21 Days.
This article is excerpted from Sams Teach Yourself Visual C++ .NET in 21 Days, by Davis Chapman (Sams Publishing, 2001, ISBN: 0672321971).
This chapter is from the book

Something that Microsoft has been proclaiming as one of the benefits of the .NET platform and the CLR since the first announcement has been the ease and capability of interacting with objects created in other languages. Sure, with COM you could already do this, but that required creating COM objects in the various languages, and jumping through the hoops that COM forced you through. So the question remains, just how easy and effortless is it to interact with objects created in other languages? That's what you'll be exploring and learning about in this article. You'll learn how to

  • Create managed C++ components that can be called from C# and VB.NET applications

  • Call VB.NET and C# components from managed C++ applications

  • Call CLR components from an unmanaged application

Mixing Languages: Realizing the Promise of the CLR

How does it really work? And can you go the other way, using .NET objects created in other languages in unmanaged C++ applications?

The quick answer is yes, you can use other .NET objects in unmanaged C++ applications, and you can create managed objects that can be used in other .NET languages. Although using objects created in managed C++ (or wrapped with managed C++) is much easier in other .NET languages, it's still possible to take it the other way, and use objects created in other .NET languages in both managed and unmanaged C++ applications.

Accessing and Using Managed C++ Objects in C# and VB.NET

Accessing objects created in other languages in C# and VB.NET projects is really very simple. If you've used previous versions of Visual Basic, you probably know how to add references to COM objects so that you can use those objects in your project. With VB.NET and C#, it's basically the same process that enables you to use other CLR objects, regardless of what language was used to create the objects, including managed C++.

When you create a C# (pronounced C-sharp, taken from musical notation) or VB.NET project in the Solution Explorer pane under the project node, you'll find a node labeled References. If you select and right-click this node, on the context menu you'll find the option Add Reference, which will open the Add Reference dialog (see Figure 1).

Figure 1 The Add Reference dialog.

On the .NET page, you'll find the various registered .NET objects available for use in your application. On the COM page, you'll find all the COM objects registered on your computer. On the Projects page, you'll find a list of projects in the current solution, plus you can browse to locate other objects in other projects.

After you select an object to reference, click the Select button to add it to the list of referenced objects in the bottom portion of the dialog. If you need to remove an object reference, select it in the bottom portion and click the Remove button. After you add references to all the objects you need, click OK to add all those objects as nodes below the References folder on the Solution Explorer pane.

After you add references to the objects, you can freely include them in your VB.NET or C# code. For instance, if you added a reference to a component, you would use it as follows:

MgdGetTaxForPurchase pGetTax = new MgdGetTaxForPurchase();

if (pGetTax.GetPurchaseTaxes(fPurchaseAmt, pstrCategory, ref fTaxAmt))

If you're using the component in a VB.NET application, you'd use it as follows:

Dim pGetTax as MgdGetTaxForPurchase 

pGetTax = New MgdGetTaxForPurchase()
if (pGetTax.GetPurchaseTaxes(fPurchaseAmt, pstrCategory, byref fTaxAmt))

Now, if you try to create C# and VB.NET clients for the component, you'll find that these don't quite work correctly. A few changes in the managed C++ wrapper need to be made before you can use it in C# or VB.NET applications:

  • The amount of taxes to be calculated should be returned as a result, not passed in as a parameter.

  • With the float variables, you need to use Single variable types in VB.NET. Another option is to use double variables instead of float.

After making these changes, your C# code would look like this:

MgdGetTaxForPurchase pGetTax = new MgdGetTaxForPurchase();

fTaxAmt = pGetTax.GetPurchaseTaxes(fPurchaseAmt, pstrCategory);

And the VB.NET code would look like this:

Dim pGetTax as MgdGetTaxForPurchase 

pGetTax = New MgdGetTaxForPurchase()
sgTaxAmt = pGetTax.GetPurchaseTaxes(sgPurchaseAmt, pstrCategory)

The changes you need to make to your managed C++ wrapper look like the following:

 MgdGetTaxForPurchase::GetPurchaseTaxes(float fPurchaseAmt,
      System::String* pstrCategory)
  wchar_t *pCat;
  int iLen;
  float fTax;

  // Convert the category from a BSTR to a wchar_t
  __wchar_t pCategory __gc[] = pstrCategory->ToCharArray();
  iLen = pstrCategory->get_Length();
  pCat = new wchar_t[iLen + 1];
  for (int i = 0; i < iLen; i++)
    pCat[i] = pCategory[i];
  pCat[i] = NULL;
  // Calculate the taxes due
  if (m_pTaxCalc->CalculateTaxes(fPurchaseAmt, pCat, &fTax))
    return fTax;
    return 0.0;

Accessing and Using C# and VB.NET Objects in Managed C++

Turning around the equation and trying to access objects created in C# and VB.NET from managed C++ applications is basically the same as the method you use to access the managed C++ wrapper around the COM object. You place a #using directive near the top of the source code, copy the DLL (or other object file that contains the objects) into the output directory, and then tell the compiler to use the output directory for resolving #using directives.

The biggest difference in the configuration is, if you are working with C# and VB.NET components that are part of the same project, you need to add a bin directory between the component project directory and the configuration name. For instance, if a component had been created by using C# instead ATL and managed C++, in the Pre-Build event command, instead of entering the command you did enter, you would enter the following:

copy "$(SolutionDir)\bin\$(ConfigurationName)\ProjectName.DLL"

The same string would have been entered if the component had been created using VB.NET. What this pre-build event does is make a copy of the DLL in which the component is packaged to the output directory of the client project. This is done before the client project is built, so that the client project can resolve its #using directive to the output directory.

Accessing and Using C# and VB.NET Objects in Unmanaged C++

Things get complicated when you try to access managed components from an unmanaged application. It's similar to putting a managed wrapper around your ATL COM component, only this time you're putting a managed C++ wrapper around the CLR components.

You have to create a managed C++ class as part of the unmanaged application. This managed C++ class functions as an interface between the CLR components, regardless of what language they were created with, and the rest of the unmanaged application. To keep things as simple as possible, you don't want your managed C++ class to be garbage collected, and you'll want to place all #using directives into the source code file (.cpp) instead of into the header file. This simplifies things because any other unmanaged C++ code in the application that needs to access the managed class will need to include the header file of the managed class. If the header file contains the #using directives or any managed extension keywords (such as the __gc keyword necessary to make the class garbage collected), those classes will also need to be compiled as managed C++ to understand those directives and keywords. The alternative is that you define all those by using the #define preprocessor directive, replacing those keywords with benign alternatives (such as white space).

You have to turn off the use of precompiled headers in your application, as well as the edit and continue while debugging capabilities. Depending on your unmanaged project, you may have to adjust some other configuration options. When you try to compile the project, if another option needs to be set to a different setting, the compiler will give you an error message showing the compiler option that needs to be set differently. It displays the compiler options in command-line form (the flags that would be passed to the compiler if you were invoking it from the DOS prompt), so you may have to search around the project properties dialog to find the option that needs to be set differently.

Another factor that needs to be taken into consideration is variable compatibility. One key variable type that may cause you problems is string type. For the most part, if the CLR components that you are calling require a string variable as a parameter to a method, you can pass it a wchar_t array as follows:

wchar_t wszString[20];

  • + Share This
  • 🔖 Save To Your Account