【问题标题】:Using c library variable/struct member in C++ class member function在 C++ 类成员函数中使用 C 库变量/结构成员
【发布时间】:2014-05-22 01:27:46
【问题描述】:

我最近开始阅读有关 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 仅将 typedef 用于 struct snd_pcm_t,但它是在其他地方定义的。我对么?有没有办法解决这个问题?一般来说,如果我们在 C++ 类中包含一些 c 库函数,哪些是要记住/避免的?谢谢

【问题讨论】:

    标签: c++ c alsa


    【解决方案1】:

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

    要获取 PCM 设备的名称,请致电 snd_pcm_name

    cout << snd_pcm_name(pcm_handle) << endl;
    

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

    【讨论】:

    • snd_pcm_name(pcm_handle) 有效。正如你所说的 struct _snd_pcm 的布局可能会改变,它没有暴露在库 api 中并且它的实现是隐藏的?
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      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;
          ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-15
        相关资源
        最近更新 更多