C/C++中的不透明類型(opaque type)

這兩天看關於NNAPI的文檔,發現有下面的代碼:ui

typedef struct ANeuralNetworksModel ANeuralNetworksModel;

文檔是這樣寫的:.net

ANeuralNetworksModel is an opaque type that contains a description of the mathematical operations that constitute the model.code

最開始對不透明類型(opaque type)不太理解,而且代碼中也搜不到對ANeuralNetworksModel的具體定義。 後來看了源代碼才知道這是用不透明類型來實現抽象的方式。blog

ANeuralNetworksModel *model;
ANeuralNetworksModel_create(&model);
int ANeuralNetworksModel_create(ANeuralNetworksModel** model) {
    initVLogMask();
    if (!model) {
        LOG(ERROR) << "ANeuralNetworksModel_create passed a nullptr";
        return ANEURALNETWORKS_UNEXPECTED_NULL;
    }
    ModelBuilder* m = new ModelBuilder();
    if (m == nullptr) {
        *model = nullptr;
        return ANEURALNETWORKS_OUT_OF_MEMORY;
    }
    *model = reinterpret_cast<ANeuralNetworksModel*>(m);
    return ANEURALNETWORKS_NO_ERROR;
}

上面的代碼中,model實現了對具體類型的隱藏,代碼中對ANeuralNetworksModel的任何使用都會首先轉換成ModelBuilder,也就是說外部看到的是ANeuralNetworksModel,內部使用的是ModelBuilder,而且外部不知道內部任何信息。ip

參考: https://blog.csdn.net/clannad_wawa/article/details/40922097文檔

相關文章
相關標籤/搜索