在C ++类成员函数中使用c库变量/ struct成员

时间:2014-04-09 03:55:27

标签: c++ c alsa

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

3 个答案:

答案 0 :(得分:2)

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

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

cout << snd_pcm_name(pcm_handle) << endl;

(ALSA中的所有内容都需要这样的函数调用。)

答案 1 :(得分:0)

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

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

答案 2 :(得分:-1)

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