Hi all,
I've experienced a problem when passing a smart-pointer (_com_ptr_t)
by value to another function using managed extensions. This only seems
to happen if the object is created via new. Can anyone confirm this
issue?
I wrote a little program that demonstrates this behaviour:
Main.cpp:
=========
#include "stdafx.h"
#import "msado25.tlb" rename_namespace("ADO") named_guids
rename("EOF", "EndOfFile")
#include "Test.h"
#using <mscorlib.dll>
using namespace System;
using namespace System::Runtime::InteropServices;
int main(int argc, char* argv[])
{
try
{
// CREATE A COM-OBJECT
CoInitialize(NULL);
ADO::_ConnectionPtr con(ADO::CLSID_Connection);
con->Open("PROVIDER=SQLOLEDB; SERVER=sqltest1\\dbserv1;
DATABASE=Netzdaten;Trusted_Connection=Yes;App=MCDa taSourceService",
"", "", 0);
CTest test;
test.TestMe(con); // WORKS FINE
CTest *ptest = new CTest();
ptest->TestMe(con); // THIS LINE DESTROYS THE UNDERLYING COM-OBJECT
(con)
// THE NEXT LINE THROWS A
System.NullReferenceException DUE TO THE FACT THAT THE COM-OBJECT HAS
BEEN DESTROYED
printf("connection string = %s\n",
(LPCTSTR)con->GetConnectionString());
}
catch (_com_error e)
{
_bstr_t bstrDescription = e.Description();
}
catch (Exception *e)
{
System::Console::WriteLine("\n\nException:");
System::Console::WriteLine(e->ToString());
}
return 0;
}
Test.h
=======
#ifndef _Test
#define _Test
#import "msado25.tlb" rename_namespace("ADO") named_guids
rename("EOF", "EndOfFile")
class CTest
{
public:
virtual void TestMe(ADO::_ConnectionPtr con);
};
Test.cpp
========
#include "stdafx.h"
#include "Test.h"
void CTest::TestMe(ADO::_ConnectionPtr con)
{
printf("by value = smart-ptr-address %x\n", con.GetInterfacePtr());
printf("connection string = %s\n",
(LPCTSTR)con->GetConnectionString());
}