亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 C# 調用 C++ DLib 導致錯誤分配異常

從 C# 調用 C++ DLib 導致錯誤分配異常

C#
慕婉清6462132 2021-11-28 19:50:14
如果我直接在 C++ 中運行我的代碼,它運行得很好。但是,當我從 C# 調用它時,我收到一條錯誤的分配消息。我的 C++ 經驗非常低,但根據我閱讀和修改的所有內容,我覺得這應該可行。我的情況通過面部識別傳遞圖像路徑,然后將結果保存/序列化到磁盤并返回圖像在數組中的索引(函數:int AddImageToCollection)如果我使用 main 函數運行我的代碼,我會得到完美的結果(圖 1),但如果我通過 C# 運行它(圖 2),我會得到以下結果:我得到的是日志 4-1 但不是日志 4-2,而且 e.what() 中唯一的錯誤是“分配錯誤”。我創建了一個無參數測試函數,它被硬編碼為返回 5 并且可以工作,因此它與這個更復雜的函數隔離,我相信它必須與將數據傳遞給 const char* 相關。圖1frontal_face_detector detector = get_frontal_face_detector();shape_predictor sp;anet_type net;bool fileExists(const std::string& name) {ifstream f(name.c_str());return f.good();}void log(std::string name) {}int main(int argc, char** argv) try{string str = "C:\\images\\Me.jpg";const char* c = str.c_str();int whatIsMyIdx = AddImageToCollection(c);cout << whatIsMyIdx << endl;cin.get();}catch (std::exception& e){    cout << e.what() << endl;}int AddImageToCollection(const char* imagePath){    deserialize("shape_predictor_5_face_landmarks.dat") >> sp;    deserialize("dlib_face_recognition_resnet_model_v1.dat") >> net;    matrix<rgb_pixel> image;    string imagePathStr(imagePath);    load_image(image, imagePathStr);    std::vector<matrix<rgb_pixel>> faces;    if (fileExists("faces_in_collection.dat")) {        deserialize("faces_in_collection.dat") >> faces;    }    auto facesDetected = detector(image);    if (facesDetected.size() == 0) { return -1; }    if (facesDetected.size() > 1) { return -2; }    auto shape = sp(image, facesDetected[0]);    log("4-1");    matrix<rgb_pixel> face_chip;    extract_image_chip(image, get_face_chip_details(shape, 150, 0.25), face_chip);    log("4-2");    faces.push_back(move(face_chip));    serialize("faces_in_collection.dat") << faces;    std::vector<matrix<float, 0, 1>> face_descriptors;    if (fileExists("face_descriptors_in_collection.dat")) {        deserialize("face_descriptors_in_collection.dat") >> face_descriptors;    }
查看完整描述

1 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

你需要調整你的代碼如下

在 DLL 中

extern "C" __declspec(dllexport) int AddImageToCollection(LPCWSTR imagePath) { .... // you may need to convert from Unicode string to ANSI if you are calling function that accept ANSI strings }

并在 c# 應用程序中

[DllImport("FacialRecognition.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] public static extern int AddImageToCollection(string imagePath);

并調用你的函數

int whatIsMyIdx = AddImageToCollection(@"C:\\images\\Me.jpg");

為了使上述工作正常,不要忘記將應用程序和 Dll 編譯為 Unicode。如果它們不同,您應該調整正確的出口和進口申報。


查看完整回答
反對 回復 2021-11-28
  • 1 回答
  • 0 關注
  • 327 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號