Visual C++ Extensions 範例
此程式會顯示如何從欄位擷取值,並轉換成 C/C++ 變數。
此範例也會利用「智慧指標」,自動處理 IADORecordBinding 介面呼叫 QueryInterface
與參考計數的 COM 特定詳細資料。
若沒有智慧指標,您可以透過以下方式撰寫程式碼:
IADORecordBinding *picRs = NULL;
...
TESTHR(pRs->QueryInterface(
__uuidof(IADORecordBinding), (LPVOID*)&picRs));
...
if (picRs) picRs->Release();
有智慧指標時,您可以使用此陳述式從 IADORecordBinding
介面衍生 IADORecordBindingPtr
類型:
_COM_SMARTPTR_TYPEDEF(IADORecordBinding, __uuidof(IADORecordBinding));
並具現化指標,如下所示:
IADORecordBindingPtr picRs(pRs);
因為 Visual C++ 延伸模組是由 Recordset 物件實作,所以智慧指標 picRs
的建構函式會採用 _RecordsetPtr
指標 (pRs
)。 建構函式會使用 pRs
呼叫 QueryInterface
,以尋找 IADORecordBinding
介面。
// Visual_Cpp_Extensions_Example.cpp
// compile with: /EHsc
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
#include <icrsint.h>
_COM_SMARTPTR_TYPEDEF(IADORecordBinding, __uuidof(IADORecordBinding));
inline void TESTHR(HRESULT _hr) { if FAILED(_hr) _com_issue_error(_hr); }
class CCustomRs : public CADORecordBinding {
BEGIN_ADO_BINDING(CCustomRs)
ADO_VARIABLE_LENGTH_ENTRY2(2, adVarChar, m_ch_fname, sizeof(m_ch_fname), m_ul_fnameStatus, false)
ADO_VARIABLE_LENGTH_ENTRY2(4, adVarChar, m_ch_lname, sizeof(m_ch_lname), m_ul_lnameStatus, false)
END_ADO_BINDING()
public:
CHAR m_ch_fname[22];
CHAR m_ch_lname[32];
ULONG m_ul_fnameStatus;
ULONG m_ul_lnameStatus;
};
int main() {
::CoInitialize(NULL);
try {
_RecordsetPtr pRs("ADODB.Recordset");
CCustomRs rs;
IADORecordBindingPtr picRs(pRs);
pRs->Open(L"SELECT * FROM Employee ORDER BY lname", L"dsn=DataPubs;Trusted_Connection=yes;", adOpenStatic, adLockOptimistic, adCmdText);
TESTHR(picRs->BindToRecordset(&rs));
while (!pRs->EndOfFile) {
// Process data in the CCustomRs C++ instance variables.
printf("Name = %s %s\n",
(rs.m_ul_fnameStatus == adFldOK ? rs.m_ch_fname: "<Error>"),
(rs.m_ul_lnameStatus == adFldOK ? rs.m_ch_lname: "<Error>") );
// Move to the next row of the Recordset. Fields in the new row will
// automatically be placed in the CCustomRs C++ instance variables.
pRs->MoveNext();
}
}
catch (_com_error &e ) {
printf("Error:\n");
printf("Code = %08lx\n", e.Error());
printf("Meaning = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) e.Source());
printf("Description = %s\n", (LPCSTR) e.Description());
}
::CoUninitialize();
}