从 C# 调用 C++ DLib 导致错误分配异常

如果我直接在 C++ 中运行我的代码,它运行得很好。但是,当我从 C# 调用它时,我收到一条错误的分配消息。我的 C++ 经验非常低,但根据我阅读和修改的所有内容,我觉得这应该可行。


我的情况


通过面部识别传递图像路径,然后将结果保存/序列化到磁盘并返回图像在数组中的索引(函数:int AddImageToCollection)


如果我使用 main 函数运行我的代码,我会得到完美的结果(图 1),但如果我通过 C# 运行它(图 2),我会得到以下结果:


我得到的是日志 4-1 但不是日志 4-2,而且 e.what() 中唯一的错误是“分配错误”。我创建了一个无参数测试函数,它被硬编码为返回 5 并且可以工作,因此它与这个更复杂的函数隔离,我相信它必须与将数据传递给 const char* 相关。


图1


frontal_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;

    }


慕婉清6462132
浏览 279回答 1
1回答

绝地无双

你需要调整你的代码如下在 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",&nbsp;CallingConvention&nbsp;=&nbsp;CallingConvention.Cdecl,&nbsp;CharSet&nbsp;=&nbsp;CharSet.Unicode)]&nbsp;public&nbsp;static&nbsp;extern&nbsp;int&nbsp;AddImageToCollection(string&nbsp;imagePath);并调用你的函数int&nbsp;whatIsMyIdx&nbsp;=&nbsp;AddImageToCollection(@"C:\\images\\Me.jpg");为了使上述工作正常,不要忘记将应用程序和 Dll 编译为 Unicode。如果它们不同,您应该调整正确的出口和进口申报。
打开App,查看更多内容
随时随地看视频慕课网APP