共用方式為


HOW TO:封送處理 ADO.NET 的 ANSI 字串 (C++/CLI)

示範如何將原生字串 (char *) 加入至資料庫中,以及如何將 System.String 從資料庫封送處理為原生字串。

範例

在此範例中,會建立類別 DatabaseClass,使其與 ADO.NET DataTable 物件互動。 請注意,這個類別是原生 C++ class (相較於 ref class 或 value class 而言)。 因為要從機器碼使用此類別,而且無法在機器碼中使用 Managed 型別,所以這點是必要的。 如類別宣告之前的 #pragma managed 指示詞所表示,這個類別將會編譯成以 CLR 為目標。 如需這個指示詞的詳細資訊,請參閱 managed, unmanaged

請注意 DatabaseClass 類別的私用成員:gcroot<DataTable ^> table。 由於原生型別不能包含 Managed 型別,所以 gcroot 關鍵字是必要的。 如需 gcroot 的詳細資訊,請參閱 HOW TO:以原生型別宣告控制代碼

如同 main 之前的 #pragma unmanaged 指示詞所表示的,此範例中的其餘程式碼都是原生 C++ 程式碼。 在此範例中,會建立 DatabaseClass 的新執行個體並呼叫它的方法,以建立資料表,並在此資料表中填入一些資料列。 請注意,原生 C++ 字串會傳遞至資料庫資料行 StringCol 做為其值。 在 DatabaseClass 之內,會使用 System.Runtime.InteropServices 命名空間中可以找到的封送處理功能,將這些字串封送處理到 Managed 字串。 具體而言,PtrToStringAnsi 方法是用於將 char * 封送處理為 String,而 StringToHGlobalAnsi 方法則用於將 String 封送處理為 char *。

注意事項注意事項

StringToHGlobalAnsi 所配置的記憶體必須透過呼叫 FreeHGlobalGlobalFree 才能取消配置。

// 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;
}
  
  

編譯程式碼

  • 若要從命令列編譯程式碼,請將程式碼範例儲存於名為 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 有關的安全性問題之詳細資訊,請參閱Securing ADO.NET Applications

請參閱

參考

System.Runtime.InteropServices

其他資源

使用 ADO.NET 進行資料存取 (C++/CLI)

ADO.NET

互通性

原生和 .NET 互通性