I have C# object in a DLL. I call a method of this object via COM from MFC DLL. like this:
BOOL CForwarder::InitMyManagedFlex()
{
// Initialize COM.
HRESULT hr = CoInitialize(NULL);
// Create the interface pointer.
IForwarderPtr pIFwd(__uuidof(MyForwarder));
long lResult = 0;
VARIANT_BOOL ret = FALSE;
BSTR bstr = AsciiToBSTR("AAA");
// Call the Add method.
pIFwd->Start(bstr, &ret);
SysFreeString(bstr);
wprintf(L"The result is %d\n", ret);
// Uninitialize COM.
CoUninitialize();
return (ret == VARIANT_TRUE) ? TRUE : FALSE;
}
Then after a while I call another method SetTimeFormat in exactly the same manner. The problem is that every time I call in this manner I instantiate a new C# object, but in fact I am trying to reach the same object that was created the first time and simply set one of its properties to a different value.
The problem seems to be in this line:
IForwarderPtr pIFwd(__uuidof(MyForwarder));
So how do I get the interface to the same C# object instead of creating a new one?
// Create the interface pointer.
IForwarderPtr pIFwd(__uuidof(MyForwarder));
Actually that line does two things. It creates the COM object whose UUID/ClassID is MyForwarder
and stores the result in pIFwd
.
If you don't want to create it each time try this:
IForwarderPtr pIFwd(__uuidof(MyForwarder));
pIFwd->Start(bstr, &ret);
.
.
.
.
pIFwd->SetTimeFormat (....)
.
.
.
SysFreeString(bstr);
wprintf(L"The result is %d\n", ret);
// Uninitialize COM.
CoUninitialize();
You can move the following statements to your constructor
HRESULT hr = CoInitialize(NULL);
_pIFwd(__uuidof(MyForwarder)); //where _pIFwd is a member variable of your class
& the statement CoUninitialize() to your destructor. Add IForwardPtr as a member variable of your class.
This way you will be able to re-use the same instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.