这是我为构造函数提供的代码:
LmiVideoCapturer* LmiVideoCapturerConstruct_(LmiVideoCapturer* x, const void* implementation)
{
std::vector<LmiVideoCapturerInfo> &deviceList = LmiVideoCapturerDeviceList::Instance();
LmiVideoCapturerInfo &capturerInfo = LmiVideoCapturerInfo();
for (std::vector<LmiVideoCapturerInfo>::iterator it = deviceList.begin(); it != deviceList.end(); it++){
if (LmiStringCompare(&it->uniqueId, &x->uniqueId) == 0){
capturerInfo = *it;
break;
}
}
if (capturerInfo.uniqueId.size > 0){
x->isBuiltin = LMI_TRUE;
// set basic device info
LmiStringAssign(&x->name, &capturerInfo.name);
LmiStringAssign(&x->model, &capturerInfo.model);
LmiStringAssign(&x->manufacturer, &capturerInfo.manufacturer);
x->position = capturerInfo.position;
// set video capabilities
LmiAllocator *a = LmiMallocAllocatorGetDefault();
Platform::String ^deviceId = LmiStringWinRTString(&capturerInfo.uniqueId, a);
XTRACE(L"=========================Will call from LMIVideoCapturerConstruct\n");
LmiVideoCapturerWinRTImplementation ^impl = ref new LmiVideoCapturerWinRTImplementation(deviceId);
if (impl->Initialize()){
//TODO will need to save impl inside a pin_ptr (pinned pointer) so it will not be deconstructed by the GC
x->implementation = reinterpret_cast<void*>(impl);
LmiVideoCapturerCapability capability;
LmiVideoCapturerCapabilityConstructDefault(&capability, a);
capability.height = impl->encodingProfile->Video->Height;
capability.width = impl->encodingProfile->Video->Width;
LmiMediaFormat format;
LmiMediaFormatConstructFromNative(&format, impl->encodingProfile->Video->ProfileId);
LmiVectorPushBack(LmiMediaFormat)(&capability.formats, &format);
double usecs = ((double)impl->encodingProfile->Video->FrameRate->Denominator / impl->encodingProfile->Video->FrameRate->Numerator) * LMI_USECS_PER_SEC;
LmiTimeRange range;
LmiTimeRangeConstruct(&range, LmiTimeUsecs(usecs), LmiTimeUsecs(usecs));
LmiVectorPushBack(LmiTimeRange)(&capability.ranges, &range);
LmiVectorPushBack(LmiVideoCapturerCapability)(&x->capabilities, &capability);
return x;
}
}
return nullptr;
}
现在我想将“impl”保存在某个地方,这就是为什么我将它保存在 X 中,我将在函数结束时返回。但是一旦这个函数结束,GC 就会调用这个对象的解构器。当它被调用时,如何设置这个对象被 GC 避免?
编辑:在互联网上搜索数小时后,我注意到 c++ 有一个叫做固定指针(pin_ptr)的东西,但我在上面找到的所有示例都显示了在内部保存 int 数组。是否可以将对象保存在固定指针中?