2014-04-09 75 views
1

我最近開始閱讀關於alsa api的內容。我試圖寫用於打開缺省設備,並讀取像最大速率基本參數,信道數量等在C++類的成員函數中使用c庫變量/ struct成員

我的類的頭文件是一個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庫函數?謝謝

回答

0

你的代碼沒有問題。只是,有一種struct _snd_pcm丟失聲明,你只包括頭具有的typedef:typedef struct _snd_pcm snd_pcm_t;

你可以做的是查找(也許在互聯網上或在手冊中)爲具有struct _snd_pcm聲明,包括它的頭在你的代碼中。

2

struct _snd_pcm的佈局故意隱藏程序,因爲它可能會更改爲新的庫版本。

爲了得到一個PCM設備的名稱,叫snd_pcm_name

cout << snd_pcm_name(pcm_handle) << endl; 

(在ALSA幾乎一切需要這樣的函數調用)

+0

snd_pcm_name(pcm_handle)的作品。正如你所說struct _snd_pcm的佈局可能會改變,它不會暴露在庫API中,並且其實現是隱藏的? – sap

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

ALSA頭已經有'extern「C」'。 –