在c++类成员函数中使用c库变量/结构成员
Using c library variable/struct member in C++ class member function
我最近开始阅读有关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;
...
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查