根据百度的语音识别例子,展示C如何调用C++库

刚才无聊摆弄了一下百度的语音识别RestAPI,看到语音识别的Sample是用C++写的,一共有三个组件,libcurl.a、libjson.a、base64.cpp,在编译时出现Json::Reader未定义引用的错误。想着还是用C重写一下这个例子吧。RestAPI的调用方式是先用过SKey获得Token,然后把音频(例如:test.pcm)通过Base64编码成字符串附加到地址中,通过curl的方式post到语音识别平台,返回JSON获取音频结果。作者重写代码时json组件没有用libjson.a,而是用的cJSON组件,会在另一篇文章展示如何用cJSON。Base64的编码功能还是用的Base64.cpp这个文件。

因为C语言没有类的概念,C代码在调用C++编译的库的时候要在C++代码中添加一段可以被C调用的函数。在对音频编码时需要用到的是

std::string base64_encode(unsigned char const *bytes_to_encode, unsigned int in_len)

这个方法,看到是string类型,C标准没有这个类型,所以我们在写被C调用的方法时要把string转换成char*,作者不太会说,所以还是用代码来说话吧。

#ifdef __cplusplus

extern "C" {

#endif

//把被调用的方法放在这里

char *callBase64Encode(unsigned char const *bytes_to_encode, unsigned int in_len)

{

std::string ret;

ret = base64_encode(bytes_to_encode, in_len);

char *c;

const int len = ret.length();

c = new char[len + 1];

strcpy(c, ret.c_str());

return c;

}

#ifdef __cplusplus

}

#endif

在base64.cpp文件中添加上面的代码,上面的代码就是定义可以被C语言调用的方法,方法开头定义的是char*,因为代码的后部分获取到编码的值后通过

char *c;

const int len = ret.length();

c = new char[len + 1];

strcpy(c, ret.c_str());

return c;

这几行代码将string类型的字符串转换成了char*类型的字符串。

然后在base64.h头文件中添加

#ifdef __cplusplus

extern "C" {

#endif

char *callBase64Encode(unsigned char const *bytes_to_encode, unsigned int in_len);

#ifdef __cplusplus

}

#endif

上方法,在C代码中引用#include 这个头文件,然后通过

g++ base64.cpp -fPIC -shared -o libase64.so

把base64代码编译成libase64.so链接库文件,再通过

gcc cJSON.c sample.c -L . -lase64 -lstdc++ -o sample -lm

我们的sample.c代码就可以调用libase64.so的方法了,结果如下:

0?wx_fmt=png

json的speech值就是对音频进行编码后的字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值