ADO.NET によるデータ アクセス (C++/CLI)

ADO.NET は、データ アクセス用の .NET Framework API であり、以前のデータ アクセス ソリューションと比類のないパワーと使いやすさを提供します。 このセクションでは、ネイティブ型のマーシャリングなど、Visual C++ ユーザーに固有の ADO.NET に関連する問題の一部について説明します。

ADO.NET は、共通言語ランタイム (CLR) で実行されます。 したがって、ADO.NET と対話するアプリケーションでも、CLR をターゲットとする必要があります。 ただし、これは、ネイティブ アプリケーションで ADO.NET を使用できないことを意味するわけではありません。 これらの例は、ネイティブ コードから ADO.NET データベースと対話する方法を示します。

ADO.NET の ANSI 文字列をマーシャリングする

ネイティブ文字列 (char *) をデータベースに追加する方法と、System.String をデータベースからネイティブ文字列にマーシャリングする方法について説明します。

この例では、ADO.NET の DataTable オブジェクトと対話するために、クラス DatabaseClass を作成します。 このクラスは、(ref classvalue class との対比として) ネイティブ C++ class であることに注意してください。 これが必要なのは、このクラスをネイティブ コードから使用する必要があり、ネイティブ コードではマネージド型を使用できないためです。 このクラスは、クラス宣言の前にある #pragma managed ディレクティブによって示されているように、CLR をターゲットとするようコンパイルされます。 このディレクティブの詳細については、managed、unmanaged に関する記事を参照してください。

DatabaseClass クラスのプライベート メンバー (gcroot<DataTable ^> table) をメモしておきます。 ネイティブ型にはマネージド型を含めることができないため、gcroot キーワードが必要です。 gcroot の詳細については、「方法: ネイティブ型でハンドルを宣言する」を参照してください。

この例の残りのコードは、main の前にある #pragma unmanaged ディレクティブで示されているように、ネイティブ C++ コードです。 この例では、DatabaseClass の新しいインスタンスを作成し、そのメソッドを呼び出してテーブルを作成して、そのテーブルのいくつかの行にデータを入力します。 ネイティブ C++ 文字列は、データベース列 StringCol の値として渡されることに注意してください。 DatabaseClass 内部では、これらの文字列は、System.Runtime.InteropServices 名前空間にあるマーシャリング機能を使用して、マネージド文字列にマーシャリングされます。 具体的には、char *String にマーシャリングするのにメソッド PtrToStringAnsi が使用され、Stringchar * にマーシャリングするのにメソッド StringToHGlobalAnsi が使用されます。

Note

StringToHGlobalAnsi によって割り当てられたメモリの割り当てを解除するには、FreeHGlobal または GlobalFree のいずれかを呼び出します。

// adonet_marshal_string_native.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;

#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;

#define MAXCOLS 100

#pragma managed
class DatabaseClass
{
public:
    DatabaseClass() : table(nullptr) { }

    void AddRow(char *stringColValue)
    {
        // Add a row to the table.
        DataRow ^row = table->NewRow();
        row["StringCol"] = Marshal::PtrToStringAnsi(
            (IntPtr)stringColValue);
        table->Rows->Add(row);
    }

    void CreateAndPopulateTable()
    {
        // Create a simple DataTable.
        table = gcnew DataTable("SampleTable");

        // Add a column of type String to the table.
        DataColumn ^column1 = gcnew DataColumn("StringCol",
            Type::GetType("System.String"));
        table->Columns->Add(column1);
    }

    int GetValuesForColumn(char *dataColumn, char **values,
        int valuesLength)
    {
        // Marshal the name of the column to a managed
        // String.
        String ^columnStr = Marshal::PtrToStringAnsi(
                (IntPtr)dataColumn);

        // Get all rows in the table.
        array<DataRow ^> ^rows = table->Select();
        int len = rows->Length;
        len = (len > valuesLength) ? valuesLength : len;
        for (int i = 0; i < len; i++)
        {
            // Marshal each column value from a managed string
            // to a char *.
            values[i] = (char *)Marshal::StringToHGlobalAnsi(
                (String ^)rows[i][columnStr]).ToPointer();
        }

        return len;
    }

private:
    // Using gcroot, you can use a managed type in
    // a native class.
    gcroot<DataTable ^> table;
};

#pragma unmanaged
int main()
{
    // Create a table and add a few rows to it.
    DatabaseClass *db = new DatabaseClass();
    db->CreateAndPopulateTable();
    db->AddRow("This is string 1.");
    db->AddRow("This is string 2.");

    // Now retrieve the rows and display their contents.
    char *values[MAXCOLS];
    int len = db->GetValuesForColumn(
        "StringCol", values, MAXCOLS);
    for (int i = 0; i < len; i++)
    {
        cout << "StringCol: " << values[i] << endl;

        // Deallocate the memory allocated using
        // Marshal::StringToHGlobalAnsi.
        GlobalFree(values[i]);
    }

    delete db;

    return 0;
}
StringCol: This is string 1.
StringCol: This is string 2.

コードのコンパイル

  • コマンド ラインからコードをコンパイルするには、コード例を adonet_marshal_string_native.cpp という名前のファイルに保存し、次のステートメントを入力します。

    cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_string_native.cpp
    

ADO.NET の BSTR 文字列をマーシャリングする

COM 文字列 (BSTR) をデータベースに追加する方法と、System.String をデータベースから BSTR にマーシャリングする方法について説明します。

この例では、ADO.NET の DataTable オブジェクトと対話するために、クラス DatabaseClass を作成します。 このクラスは、(ref classvalue class との対比として) ネイティブ C++ class であることに注意してください。 これが必要なのは、このクラスをネイティブ コードから使用する必要があり、ネイティブ コードではマネージド型を使用できないためです。 このクラスは、クラス宣言の前にある #pragma managed ディレクティブによって示されているように、CLR をターゲットとするようコンパイルされます。 このディレクティブの詳細については、managed、unmanaged に関する記事を参照してください。

DatabaseClass クラスのプライベート メンバー (gcroot<DataTable ^> table) をメモしておきます。 ネイティブ型にはマネージド型を含めることができないため、gcroot キーワードが必要です。 gcroot の詳細については、「方法: ネイティブ型でハンドルを宣言する」を参照してください。

この例の残りのコードは、main の前にある #pragma unmanaged ディレクティブで示されているように、ネイティブ C++ コードです。 この例では、DatabaseClass の新しいインスタンスを作成し、そのメソッドを呼び出してテーブルを作成して、そのテーブルのいくつかの行にデータを入力します。 COM 文字列は、データベース列 StringCol の値として渡されることに注意してください。 DatabaseClass 内部では、これらの文字列は、System.Runtime.InteropServices 名前空間にあるマーシャリング機能を使用して、マネージド文字列にマーシャリングされます。 具体的には、BSTRString にマーシャリングするのにメソッド PtrToStringBSTR が使用され、StringBSTR にマーシャリングするのにメソッド StringToBSTR が使用されます。

Note

StringToBSTR によって割り当てられたメモリの割り当てを解除するには、FreeBSTR または SysFreeString のいずれかを呼び出します。

// adonet_marshal_string_bstr.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;

#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;

#define MAXCOLS 100

#pragma managed
class DatabaseClass
{
public:
    DatabaseClass() : table(nullptr) { }

    void AddRow(BSTR stringColValue)
    {
        // Add a row to the table.
        DataRow ^row = table->NewRow();
        row["StringCol"] = Marshal::PtrToStringBSTR(
            (IntPtr)stringColValue);
        table->Rows->Add(row);
    }

    void CreateAndPopulateTable()
    {
        // Create a simple DataTable.
        table = gcnew DataTable("SampleTable");

        // Add a column of type String to the table.
        DataColumn ^column1 = gcnew DataColumn("StringCol",
            Type::GetType("System.String"));
        table->Columns->Add(column1);
    }

    int GetValuesForColumn(BSTR dataColumn, BSTR *values,
        int valuesLength)
    {
        // Marshal the name of the column to a managed
        // String.
        String ^columnStr = Marshal::PtrToStringBSTR(
                (IntPtr)dataColumn);

        // Get all rows in the table.
        array<DataRow ^> ^rows = table->Select();
        int len = rows->Length;
        len = (len > valuesLength) ? valuesLength : len;
        for (int i = 0; i < len; i++)
        {
            // Marshal each column value from a managed string
            // to a BSTR.
            values[i] = (BSTR)Marshal::StringToBSTR(
                (String ^)rows[i][columnStr]).ToPointer();
        }

        return len;
    }

private:
    // Using gcroot, you can use a managed type in
    // a native class.
    gcroot<DataTable ^> table;
};

#pragma unmanaged
int main()
{
    // Create a table and add a few rows to it.
    DatabaseClass *db = new DatabaseClass();
    db->CreateAndPopulateTable();

    BSTR str1 = SysAllocString(L"This is string 1.");
    db->AddRow(str1);

    BSTR str2 = SysAllocString(L"This is string 2.");
    db->AddRow(str2);

    // Now retrieve the rows and display their contents.
    BSTR values[MAXCOLS];
    BSTR str3 = SysAllocString(L"StringCol");
    int len = db->GetValuesForColumn(
        str3, values, MAXCOLS);
    for (int i = 0; i < len; i++)
    {
        wcout << "StringCol: " << values[i] << endl;

        // Deallocate the memory allocated using
        // Marshal::StringToBSTR.
        SysFreeString(values[i]);
    }

    SysFreeString(str1);
    SysFreeString(str2);
    SysFreeString(str3);
    delete db;

    return 0;
}
StringCol: This is string 1.
StringCol: This is string 2.

コードのコンパイル

  • コマンド ラインからコードをコンパイルするには、コード例を adonet_marshal_string_native.cpp という名前のファイルに保存し、次のステートメントを入力します。

    cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_string_native.cpp
    

ADO.NET の Unicode 文字列をマーシャリングする

Unicode 文字列 (wchar_t *) をデータベースに追加する方法と、System.String をデータベースからネイティブの Unicode 文字列にマーシャリングする方法について説明します。

この例では、ADO.NET の DataTable オブジェクトと対話するために、クラス DatabaseClass を作成します。 このクラスは、(ref classvalue class との対比として) ネイティブ C++ class であることに注意してください。 これが必要なのは、このクラスをネイティブ コードから使用する必要があり、ネイティブ コードではマネージド型を使用できないためです。 このクラスは、クラス宣言の前にある #pragma managed ディレクティブによって示されているように、CLR をターゲットとするようコンパイルされます。 このディレクティブの詳細については、managed、unmanaged に関する記事を参照してください。

DatabaseClass クラスのプライベート メンバー (gcroot<DataTable ^> table) をメモしておきます。 ネイティブ型にはマネージド型を含めることができないため、gcroot キーワードが必要です。 gcroot の詳細については、「方法: ネイティブ型でハンドルを宣言する」を参照してください。

この例の残りのコードは、main の前にある #pragma unmanaged ディレクティブで示されているように、ネイティブ C++ コードです。 この例では、DatabaseClass の新しいインスタンスを作成し、そのメソッドを呼び出してテーブルを作成して、そのテーブルのいくつかの行にデータを入力します。 Unicode C++ 文字列は、データベース列 StringCol の値として渡されることに注意してください。 DatabaseClass 内部では、これらの文字列は、System.Runtime.InteropServices 名前空間にあるマーシャリング機能を使用して、マネージド文字列にマーシャリングされます。 具体的には、wchar_t *String にマーシャリングするのにメソッド PtrToStringUni が使用され、Stringwchar_t * にマーシャリングするのにメソッド StringToHGlobalUni が使用されます。

Note

StringToHGlobalUni によって割り当てられたメモリの割り当てを解除するには、FreeHGlobal または GlobalFree のいずれかを呼び出します。

// adonet_marshal_string_wide.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;

#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;

#define MAXCOLS 100

#pragma managed
class DatabaseClass
{
public:
    DatabaseClass() : table(nullptr) { }

    void AddRow(wchar_t *stringColValue)
    {
        // Add a row to the table.
        DataRow ^row = table->NewRow();
        row["StringCol"] = Marshal::PtrToStringUni(
            (IntPtr)stringColValue);
        table->Rows->Add(row);
    }

    void CreateAndPopulateTable()
    {
        // Create a simple DataTable.
        table = gcnew DataTable("SampleTable");

        // Add a column of type String to the table.
        DataColumn ^column1 = gcnew DataColumn("StringCol",
            Type::GetType("System.String"));
        table->Columns->Add(column1);
    }

    int GetValuesForColumn(wchar_t *dataColumn, wchar_t **values,
        int valuesLength)
    {
        // Marshal the name of the column to a managed
        // String.
        String ^columnStr = Marshal::PtrToStringUni(
                (IntPtr)dataColumn);

        // Get all rows in the table.
        array<DataRow ^> ^rows = table->Select();
        int len = rows->Length;
        len = (len > valuesLength) ? valuesLength : len;
        for (int i = 0; i < len; i++)
        {
            // Marshal each column value from a managed string
            // to a wchar_t *.
            values[i] = (wchar_t *)Marshal::StringToHGlobalUni(
                (String ^)rows[i][columnStr]).ToPointer();
        }

        return len;
    }

private:
    // Using gcroot, you can use a managed type in
    // a native class.
    gcroot<DataTable ^> table;
};

#pragma unmanaged
int main()
{
    // Create a table and add a few rows to it.
    DatabaseClass *db = new DatabaseClass();
    db->CreateAndPopulateTable();
    db->AddRow(L"This is string 1.");
    db->AddRow(L"This is string 2.");

    // Now retrieve the rows and display their contents.
    wchar_t *values[MAXCOLS];
    int len = db->GetValuesForColumn(
        L"StringCol", values, MAXCOLS);
    for (int i = 0; i < len; i++)
    {
        wcout << "StringCol: " << values[i] << endl;

        // Deallocate the memory allocated using
        // Marshal::StringToHGlobalUni.
        GlobalFree(values[i]);
    }

    delete db;

    return 0;
}
StringCol: This is string 1.
StringCol: This is string 2.

コードのコンパイル

  • コマンド ラインからコードをコンパイルするには、コード例を adonet_marshal_string_wide.cpp という名前のファイルに保存し、次のステートメントを入力します。

    cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_string_wide.cpp
    

ADO.NET の VARIANT をマーシャリングする

ネイティブの VARIANT をデータベースに追加する方法と、System.Object をデータベースからネイティブの VARIANT にマーシャリングする方法について説明します。

この例では、ADO.NET の DataTable オブジェクトと対話するために、クラス DatabaseClass を作成します。 このクラスは、(ref classvalue class との対比として) ネイティブ C++ class であることに注意してください。 これが必要なのは、このクラスをネイティブ コードから使用する必要があり、ネイティブ コードではマネージド型を使用できないためです。 このクラスは、クラス宣言の前にある #pragma managed ディレクティブによって示されているように、CLR をターゲットとするようコンパイルされます。 このディレクティブの詳細については、managed、unmanaged に関する記事を参照してください。

DatabaseClass クラスのプライベート メンバー (gcroot<DataTable ^> table) をメモしておきます。 ネイティブ型にはマネージド型を含めることができないため、gcroot キーワードが必要です。 gcroot の詳細については、「方法: ネイティブ型でハンドルを宣言する」を参照してください。

この例の残りのコードは、main の前にある #pragma unmanaged ディレクティブで示されているように、ネイティブ C++ コードです。 この例では、DatabaseClass の新しいインスタンスを作成し、そのメソッドを呼び出してテーブルを作成して、そのテーブルのいくつかの行にデータを入力します。 ネイティブの VARIANT 型は、データベース列 ObjectCol の値として渡されることに注意してください。 DatabaseClass 内部では、これらの VARIANT 型は、System.Runtime.InteropServices 名前空間にあるマーシャリング機能を使用して、マネージド文字列にマーシャリングされます。 具体的には、VARIANTObject にマーシャリングするのにメソッド GetObjectForNativeVariant が使用され、ObjectVARIANT にマーシャリングするのにメソッド GetNativeVariantForObject が使用されます。

// adonet_marshal_variant.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;

#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;

#define MAXCOLS 100

#pragma managed
class DatabaseClass
{
public:
    DatabaseClass() : table(nullptr) { }

    void AddRow(VARIANT *objectColValue)
    {
        // Add a row to the table.
        DataRow ^row = table->NewRow();
        row["ObjectCol"] = Marshal::GetObjectForNativeVariant(
            IntPtr(objectColValue));
        table->Rows->Add(row);
    }

    void CreateAndPopulateTable()
    {
        // Create a simple DataTable.
        table = gcnew DataTable("SampleTable");

        // Add a column of type String to the table.
        DataColumn ^column1 = gcnew DataColumn("ObjectCol",
            Type::GetType("System.Object"));
        table->Columns->Add(column1);
    }

    int GetValuesForColumn(wchar_t *dataColumn, VARIANT *values,
        int valuesLength)
    {
        // Marshal the name of the column to a managed
        // String.
        String ^columnStr = Marshal::PtrToStringUni(
                (IntPtr)dataColumn);

        // Get all rows in the table.
        array<DataRow ^> ^rows = table->Select();
        int len = rows->Length;
        len = (len > valuesLength) ? valuesLength : len;
        for (int i = 0; i < len; i++)
        {
            // Marshal each column value from a managed object
            // to a VARIANT.
            Marshal::GetNativeVariantForObject(
                rows[i][columnStr], IntPtr(&values[i]));
        }

        return len;
    }

private:
    // Using gcroot, you can use a managed type in
    // a native class.
    gcroot<DataTable ^> table;
};

#pragma unmanaged
int main()
{
    // Create a table and add a few rows to it.
    DatabaseClass *db = new DatabaseClass();
    db->CreateAndPopulateTable();

    BSTR bstr1 = SysAllocString(L"This is a BSTR in a VARIANT.");
    VARIANT v1;
    v1.vt = VT_BSTR;
    v1.bstrVal = bstr1;
    db->AddRow(&v1);

    int i = 42;
    VARIANT v2;
    v2.vt = VT_I4;
    v2.lVal = i;
    db->AddRow(&v2);

    // Now retrieve the rows and display their contents.
    VARIANT values[MAXCOLS];
    int len = db->GetValuesForColumn(
        L"ObjectCol", values, MAXCOLS);
    for (int i = 0; i < len; i++)
    {
        switch (values[i].vt)
        {
            case VT_BSTR:
                wcout << L"ObjectCol: " << values[i].bstrVal << endl;
                break;
            case VT_I4:
                cout << "ObjectCol: " << values[i].lVal << endl;
                break;
            default:
                break;
        }

    }

    SysFreeString(bstr1);
    delete db;

    return 0;
}
ObjectCol: This is a BSTR in a VARIANT.
ObjectCol: 42

コードのコンパイル

  • コマンド ラインからコードをコンパイルするには、コード例を adonet_marshal_variant.cpp という名前のファイルに保存し、次のステートメントを入力します。

    cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_variant.cpp
    

ADO.NET の SAFEARRAY をマーシャリングする

ネイティブの SAFEARRAY をデータベースに追加する方法と、マネージド配列をデータベースからネイティブの SAFEARRAY にマーシャリングする方法について説明します。

この例では、ADO.NET の DataTable オブジェクトと対話するために、クラス DatabaseClass を作成します。 このクラスは、(ref classvalue class との対比として) ネイティブ C++ class であることに注意してください。 これが必要なのは、このクラスをネイティブ コードから使用する必要があり、ネイティブ コードではマネージド型を使用できないためです。 このクラスは、クラス宣言の前にある #pragma managed ディレクティブによって示されているように、CLR をターゲットとするようコンパイルされます。 このディレクティブの詳細については、managed、unmanaged に関する記事を参照してください。

DatabaseClass クラスのプライベート メンバー (gcroot<DataTable ^> table) をメモしておきます。 ネイティブ型にはマネージド型を含めることができないため、gcroot キーワードが必要です。 gcroot の詳細については、「方法: ネイティブ型でハンドルを宣言する」を参照してください。

この例の残りのコードは、main の前にある #pragma unmanaged ディレクティブで示されているように、ネイティブ C++ コードです。 この例では、DatabaseClass の新しいインスタンスを作成し、そのメソッドを呼び出してテーブルを作成して、そのテーブルのいくつかの行にデータを入力します。 ネイティブの SAFEARRAY 型は、データベース列 ArrayIntsCol の値として渡されることに注意してください。 DatabaseClass 内部では、これらの SAFEARRAY 型は、System.Runtime.InteropServices 名前空間にあるマーシャリング機能を使用して、マネージド文字列にマーシャリングされます。 具体的には、SAFEARRAY を整数のマネージド配列にマーシャリングするのにメソッド Copy が使用され、整数のマネージド配列を SAFEARRAY にマーシャリングするのにメソッド Copy が使用されます。

// adonet_marshal_safearray.cpp
// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll
#include <comdef.h>
#include <gcroot.h>
#include <iostream>
using namespace std;

#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Runtime::InteropServices;

#define MAXCOLS 100

#pragma managed
class DatabaseClass
{
public:
    DatabaseClass() : table(nullptr) { }

    void AddRow(SAFEARRAY *arrayIntsColValue)
    {
        // Add a row to the table.
        DataRow ^row = table->NewRow();
        int len = arrayIntsColValue->rgsabound[0].cElements;
        array<int> ^arr = gcnew array<int>(len);

        int *pData;
        SafeArrayAccessData(arrayIntsColValue, (void **)&pData);
        Marshal::Copy(IntPtr(pData), arr, 0, len);
        SafeArrayUnaccessData(arrayIntsColValue);

        row["ArrayIntsCol"] = arr;
        table->Rows->Add(row);
    }

    void CreateAndPopulateTable()
    {
        // Create a simple DataTable.
        table = gcnew DataTable("SampleTable");

        // Add a column of type String to the table.
        DataColumn ^column1 = gcnew DataColumn("ArrayIntsCol",
            Type::GetType("System.Int32[]"));
        table->Columns->Add(column1);
    }

    int GetValuesForColumn(wchar_t *dataColumn, SAFEARRAY **values,
        int valuesLength)
    {
        // Marshal the name of the column to a managed
        // String.
        String ^columnStr = Marshal::PtrToStringUni(
                (IntPtr)dataColumn);

        // Get all rows in the table.
        array<DataRow ^> ^rows = table->Select();
        int len = rows->Length;
        len = (len > valuesLength) ? valuesLength : len;
        for (int i = 0; i < len; i++)
        {
            // Marshal each column value from a managed array
            // of Int32s to a SAFEARRAY of type VT_I4.
            values[i] = SafeArrayCreateVector(VT_I4, 0, 10);
            int *pData;
            SafeArrayAccessData(values[i], (void **)&pData);
            Marshal::Copy((array<int> ^)rows[i][columnStr], 0,
                IntPtr(pData), 10);
            SafeArrayUnaccessData(values[i]);
        }

        return len;
    }

private:
    // Using gcroot, you can use a managed type in
    // a native class.
    gcroot<DataTable ^> table;
};

#pragma unmanaged
int main()
{
    // Create a table and add a few rows to it.
    DatabaseClass *db = new DatabaseClass();
    db->CreateAndPopulateTable();

    // Create a standard array.
    int originalArray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    // Create a SAFEARRAY.
    SAFEARRAY *psa;
    psa = SafeArrayCreateVector(VT_I4, 0, 10);

    // Copy the data from the original array to the SAFEARRAY.
    int *pData;
    HRESULT hr = SafeArrayAccessData(psa, (void **)&pData);
    memcpy(pData, &originalArray, 40);
    SafeArrayUnaccessData(psa);
    db->AddRow(psa);

    // Now retrieve the rows and display their contents.
    SAFEARRAY *values[MAXCOLS];
    int len = db->GetValuesForColumn(
        L"ArrayIntsCol", values, MAXCOLS);
    for (int i = 0; i < len; i++)
    {
        int *pData;
        SafeArrayAccessData(values[i], (void **)&pData);
        for (int j = 0; j < 10; j++)
        {
            cout << pData[j] << " ";
        }
        cout << endl;
        SafeArrayUnaccessData(values[i]);

        // Deallocate the memory allocated using
        // SafeArrayCreateVector.
        SafeArrayDestroy(values[i]);
    }

    SafeArrayDestroy(psa);
    delete db;

    return 0;
}
0 1 2 3 4 5 6 7 8 9

コードのコンパイル

  • コマンド ラインからコードをコンパイルするには、コード例を adonet_marshal_safearray.cpp という名前のファイルに保存し、次のステートメントを入力します。

    cl /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll adonet_marshal_safearray.cpp
    

.NET Framework のセキュリティ

ADO.NET に関連するセキュリティの問題の詳細については、「ADO.NET アプリケーションのセキュリティ保護」を参照してください。

セクション​​ 説明
ADO.NET .NET プログラマにデータ アクセス サービスを公開するためのクラスのセットである ADO.NET の概要について説明します。

関連項目

C++/CLI (Visual C++) による .NET プログラミング

ネイティブと .NET の相互運用性

System.Runtime.InteropServices

相互運用性