How to: Marshal a VARIANT for ADO.NET

Demonstrates how to add a native VARIANT to a database and how to marshal a System.Object from a database to a native VARIANT.

Example

In this example, the class DatabaseClass is created to interact with an ADO.NET DataTable object. Note that this class is a native C++ class (as compared to a ref class or value class). This is necessary because we want to use this class from native code, and you cannot use managed types in native code. This class will be compiled to target the CLR, as is indicated by the #pragma managed directive preceding the class declaration. For more information on this directive, see managed, unmanaged.

Note the private member of the DatabaseClass class: gcroot<DataTable ^> table. Since native types cannot contain managed types, the gcroot keyword is necessary. For more information on gcroot, see How to: Declare Handles in Native Types.

The rest of the code in this example is native C++ code, as is indicated by the #pragma unmanaged directive preceding main. In this example, we are creating a new instance of DatabaseClass and calling its methods to create a table and populate some rows in the table. Note that native VARIANT types are being passed as values for the database column ObjectCol. Inside DatabaseClass, these VARIANT types are marshaled to managed objects using the marshaling functionality found in the System.Runtime.InteropServices namespace. Specifically, the method GetObjectForNativeVariant is used to marshal a VARIANT to an Object, and the method GetNativeVariantForObject is used to marshal an Object to a VARIANT.