我在我的项目中使用 Pylon SDK。它是 Basler 相机的 SDK。
我在 main
函数的无限 while 循环中调用 gimbalControl
函数。
在gimbalControl
中,我需要定义变量并初始化云台部件。之后,我在函数的其余部分使用那些初始化和定义的东西。以下是我的代码示例,用于阐明问题。
void gimbalControl(void)
{
try
{
// Only executed in the first iteration
if(!gimbalInitialized)
{
setupGimbal();
configConnection();
PylonInitialize();
// Create an instant camera object with the camera device found first.
CInstantCamera camera(CTlFactory::GetInstance().CreateFirstDevice());
// Open the camera before accessing any parameters
camera.Open();
// Start the grabbing of images
camera.StartGrabbing();
gimbalInitialized = true;
}
else
{
// Wait for an image and then retrieve it. A timout of 5000 ms is used.
camera.RetrieveResult(5000, ptrGrabResult, TimeoutHandling_ThrowException); // CAUSES ERROR
// Image not grabbed successfully?
if (!ptrGrabResult->GrabSucceeded())
{
cout << "Cannot capture a frame from video stream" << endl;
}
}
catch(...) // Catch all unhandled exceptions
{
printf("ERROR IN CAMERA CONNECTION\n");
}
}
我试图让这个模块基于类,但我不知道如何在类中声明相机以便稍后在对象中使用。其实我不知道这种camera
声明是什么!
当我编译这段代码时,我得到一个错误,提示camera was not declared in this scope
。
问题 1:如何在此无限循环中定义一次相机而不引发此错误?
问题 2:如何将 camera
声明为类中的私有(private)变量?
最佳答案
一种方法是在 try
block 之外使 camera
静态:
static CInstantCamera camera(CTlFactory::GetInstance().CreateFirstDevice());
try {
...
} catch (...) {
...
}
这确保 camera
对象只被初始化一次,并且在条件中的 else
的两侧保持可访问性。
要在您的类中声明camera
,请将CTlFactory::GetInstance().CreateFirstDevice()
放入初始化列表中:
class MyClass {
private:
CInstantCamera camera;
public:
MyClass() : camera(CTlFactory::GetInstance().CreateFirstDevice()) {
}
};
关于c++ - 在无限循环 C++ 中定义一次变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47928196/