在c++类成员函数中使用c库变量/结构成员

Using c library variable/struct member in C++ class member function

本文关键字:成员 变量 结构 c++ 函数      更新时间:2023-10-16

我最近开始阅读有关alsa-api的文章。我试图写一个C++类,它打开默认设备并读取基本参数,如最大速率、通道数量等。

我的类头文件是:

#include <alsa/asoundlib.h>
#include <iostream>
class AlsaParam{
    snd_pcm_t* pcm_handle;
    snd_pcm_hw_params_t* hw_param;
    ....
    public:
      int pcm_open();
       .....
};

内部pcm_open()

int AlsaParam::pcm_open(){
     int err = snd_pcm_open(&pcm_handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
     if(err > -1)
         std::cout << pcm_handle->name << std::endl;   //Just to test if it works
return err;
}

我得到以下错误:

error: invalid use of incomplete type ‘snd_pcm_t {aka struct _snd_pcm}’
std::cout << pcm_handle->name << std::endl;
                       ^
 In file included from /usr/include/alsa/asoundlib.h:54:0,
             from alsa_param.h:4,
             from alsa_param.cpp:1:
 /usr/include/alsa/pcm.h:341:16: error: forward declaration of ‘snd_pcm_t {aka struct _snd_pcm}’
  typedef struct _snd_pcm snd_pcm_t;
            ^

从这个错误中,我了解到asoundlib.h只对结构snd_pcm_t使用typedef,但它是在其他地方定义的。我说得对吗?有什么办法解决这个问题吗?一般来说,如果我们在c++类中包含一些c库函数,哪些是需要记住/避免的?感谢

struct _snd_pcm的布局故意对程序隐藏,因为它可能在新的库版本中发生更改。

要获取PCM设备的名称,请调用snd_PCM_name:

cout << snd_pcm_name(pcm_handle) << endl;

(ALSA中几乎所有的东西都需要这样的函数调用。)

您的代码没有任何问题。只是缺少了struct _snd_pcm的声明,您包含的头只有typedef:typedef struct _snd_pcm snd_pcm_t;

您可以查找(可能在互联网上或手册中)具有struct _snd_pcm声明的标头,并将其包含在代码中。

C和C++在声明语法上有一些差异。

由于您正在编译一个C++文件,但其中包含一个C头,因此您可能需要让编译器以正确的方式解释它。

试试这个:

extern "C"
{
#include <alsa/asoundlib.h>
}
#include <iostream>
class AlsaParam{
    snd_pcm_t* pcm_handle;
    snd_pcm_hw_params_t* hw_param;
    ...