Difference between revisions of "Uno/Cpp/Snippet/Function always returning an appropriate object"
From Apache OpenOffice Wiki
(Now uses the FreeReference.) |
|||
Line 3: | Line 3: | ||
// This function is environment specialized on "c++<purpose>*". | // This function is environment specialized on "c++<purpose>*". | ||
uno::Reference<uno::XInterface> create_appropriateObject(void) { | uno::Reference<uno::XInterface> create_appropriateObject(void) { | ||
− | + | cppu::FreeReference<uno::XInterface> result_Obj; | |
// We may want to open a new scope, to ensure that "result_Obj" does | // We may want to open a new scope, to ensure that "result_Obj" does | ||
Line 23: | Line 23: | ||
unsafeEnv_Obj->doThat(); | unsafeEnv_Obj->doThat(); | ||
− | // We | + | // We assign it to "result_Obj". |
− | result_Obj.set | + | // Using "result_obj" is "safe" anywhere. |
+ | result_Obj.set(unsafeEnv_Obj, SAL_NO_ACQUIRE); | ||
− | |||
// The unsafeEnv_Obj reference gets destructed here, actually calling the "release" method in the right environment. | // The unsafeEnv_Obj reference gets destructed here, actually calling the "release" method in the right environment. | ||
// The unsafeGuard gets destructed here, deactivating the "c++:unsafe" environment. | // The unsafeGuard gets destructed here, deactivating the "c++:unsafe" environment. | ||
} | } | ||
− | |||
return result_Obj; | return result_Obj; | ||
} | } |
Revision as of 11:56, 28 September 2006
Callee:
[cpp]
// This function is environment specialized on "c++<purpose>*".
uno::Reference<uno::XInterface> create_appropriateObject(void) {
cppu::FreeReference<uno::XInterface> result_Obj;
// We may want to open a new scope, to ensure that "result_Obj" does // not get destructed while "c++:unsafe" is active. { // We need to remember the callers environment, to "map-out/in" // the parameters and return values properly. uno::Environment outerEnv(uno::getCurrent());
// We activate (enter) the "c++:unsafe" environment. // Note: Any other environment suiteable for "MyUnsafeObject" would work as well. cppu::EnvGuard unsafeGuard(uno::Environment(rtl::OUString(RTL_CONSTASCII_UPARAM("c++:unsafe"))));
// This reference points to a "thread-unsafe" object. Reference<uno::XInterface> unsafeEnv_Obj(new MyUnsafeObject());
// We may do some activations on "unsafeEnv_Obj". unsafeEnv_Obj->doThis(); unsafeEnv_Obj->doThat();
// We assign it to "result_Obj". // Using "result_obj" is "safe" anywhere. result_Obj.set(unsafeEnv_Obj, SAL_NO_ACQUIRE);
// The unsafeEnv_Obj reference gets destructed here, actually calling the "release" method in the right environment. // The unsafeGuard gets destructed here, deactivating the "c++:unsafe" environment. }
return result_Obj;
}
Caller:
[cpp]
...
{
// Whatever "c++<purpose>*" we enter, the result of "create_appropriateObject" will // always match. cppu::EnvGuard cppDebug_Guard(rtl::OUString(RTL_CONSTASCII_PARAM("c++:debug")));
uno::Reference obj(create_appropriateObject());
} ...