首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言呼叫 C++ 庫實戰:百度語音識別 API 串接

     編輯:關於C語言

C 語言呼叫 C++ 庫實戰:百度語音識別 API 串接

百度語音識別 REST API 範例使用 C++ 編寫,包含 libcurl、libjson、base64.cpp。為在 C 專案中使用,需將 C++ 函數包裝為 C 可呼叫介面。

核心問題

C++ 的 std::string base64_encode(...) 回傳 std::string,C 無此類型,需轉為 char*。

解決方案:extern "C" 包裝函數

在 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

編譯與連結步驟

  1. 將 C++ 程式碼編譯為共享庫:g++ base64.cpp -fPIC -shared -o libbase64.so
  2. 編譯 C 程式並連結:gcc cJSON.c sample.c -L . -lbase64 -lstdc++ -o sample -lm

執行結果

JSON 中的 speech 欄位即為 Base64 編碼後的音訊字串。

原文連結:微信文章

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved