百度語音識別 REST API 範例使用 C++ 編寫,包含 libcurl、libjson、base64.cpp。為在 C 專案中使用,需將 C++ 函數包裝為 C 可呼叫介面。
C++ 的 std::string base64_encode(...) 回傳 std::string,C 無此類型,需轉為 char*。
在 base64.cpp 中加入:
#ifdef __cplusplus
extern "C" {
#endif
char *callBase64Encode(unsigned char const *bytes_to_encode, unsigned int in_len) {
std::string ret = base64_encode(bytes_to_encode, in_len);
const int len = ret.length();
char *c = new char[len + 1];
strcpy(c, ret.c_str());
return c;
}
#ifdef __cplusplus
}
#endif
於 base64.h 宣告:
#ifdef __cplusplus
extern "C" {
#endif
char *callBase64Encode(unsigned char const *bytes_to_encode, unsigned int in_len);
#ifdef __cplusplus
}
#endif
g++ base64.cpp -fPIC -shared -o libbase64.sogcc cJSON.c sample.c -L . -lbase64 -lstdc++ -o sample -lmJSON 中的 speech 欄位即為 Base64 編碼後的音訊字串。
原文連結:微信文章