Practical Script 4: C++ exports DLL and passes Char* value

Record the bugs encountered in the project

First, when char* is used as a function parameter, it will not be assigned directly. You need to construct a char* within the function and copy it to the input char* using the memcpy function.

VS exports the DLL and adds the header definition like this in the h file.

#ifndef PDDETECT
#define PDDETECT

//宏定义导出
#ifdef PDDETECTDLL__
#define PDDETECTDLL __declspec(dllexport)//导出
#else
#define PDDETECTDLL __declspec(dllimport)//导入
#endif 

Then add extern "C" PDDETECTDLL to the function that needs to be exported. Note that extern "C" must be added, otherwise the function will not be found when calling dynamically. Another way is to use a def file to export the function. Same as extern "C".

When calling, dynamic calling does not require h and lib files, and the function definition is directly added to the calling CPP.

typedef bool(*DpDetect)(MV3D_LP_DEPTH_DATA* , char* , int& , bool& );

Then in the function called

    HINSTANCE pdDll = LoadLibrary(L"pdDetect.dll");

    HINSTANCE pdDll = LoadLibrary(L"pdDetect.dll");
    if (pdDll==NULL) {
        cout << "调用失败" << endl;
    }
    DpDetect detect_dp = (DpDetect)GetProcAddress(pdDll, "detect_dp");
    CsDetect detect_cs = (CsDetect)GetProcAddress(pdDll, "detect_cs");
    ClDetect detect_cl = (ClDetect)GetProcAddress(pdDll, "detect_cl");

    if (detect_dp == NULL || detect_cs == NULL || detect_cl==NULL)
    {
        cout << "cant get func" << endl;
    }

As long as the function extraction is successful, you can directly use the function in the DLL.

Static calling is similar to normal calling of other libraries. Add h and lib, then include the h file and call the function directly.

Speaking of which, I did this DLL thing last year, but I almost forgot about it, so I still need to record it more.

One additional thing to mention here is that after the deep learning model is packaged into a DLL, if the GPU is called, the memory must be released in time, otherwise an error will be reported.

    DetectorItem->init_model(model_param, model_bin);
    objects = DetectorItem->detect_model(matImg);
    DetectorItem->~Detector();

There is also conversion between images cv::Mat and char*

    //char* to cv::Mat
	cv::Mat matImg = cv::Mat(nInHight, nInWide, CV_8UC3, pInClData);

    //cv::Mat to char*
    //方法一
    unsigned char* ucImg = img.data;
    char* uImg = (char*)ucImg;
    //方法二,推荐用方法2,nOutSize就是图像的尺寸,如果是灰度图就是H*W,RGB图就是H*W*3
    memcpy(pOutClData, (char*)matImg.data, nOutSize);

Guess you like

Origin blog.csdn.net/fisherisfish/article/details/132103619