0

I wrote a C++ .dll that takes in two character arrays, initializes an OpenCV DNN Net object and returns it.

//test.cpp
#include "test.h"
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

using namespace cv;
using namespace std;

EXTERN_DLL_EXPORT cv::dnn::Net TestCall(char* config_path, char* model_path) {

    cout << config_path << endl;
    cout << model_path << endl;
    cv::dnn::Net net = cv::dnn::readNetFromDarknet((cv::String)config_path, (cv::String)model_path);
    net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
    net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);

    return net;
}
//test.h
#include <iostream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
using namespace cv;
using namespace std;

EXTERN_DLL_EXPORT cv::dnn::Net TestCall(char* config_path, char* model_path);

//test.py

from ctypes import *

lib = CDLL('test.dll')
config_path = r'' #model config
model_path = r'' #trained weights
model = lib.TestCall(config_path.encode('utf-8'), model_path.encode('utf-8'))
print(model)

However, I got this unexpected output.

checkpoints\yolov3_centroid_Oct_2020_40by40_try1.weights
**boxes with question marks but I can't represent them***
Traceback (most recent call last):
  File "centroid_correct.py", line 723, in Correct
    self.model = self.cext.TestCall(self.config_path.encode('utf-8'), self.model_path.encode('utf-8'))
OSError: [WinError -529697949] Windows Error 0xe06d7363

TestCall is supposed to print out both input arrays, but only the model path is printed. But if I changed TestCall to a void function, then the code seems to run normally.

config\yolov3_centroid_Oct_2020_40by40_try1.cfg
checkpoints\yolov3_centroid_Oct_2020_40by40_try1.weights
53012224

Why does the function run normally when it is a void function, but when it is a cv::dnn:Net function it behaves abnormally? Is this an issue with ctypes' compatibility with C++?

disguisedtoast
  • 149
  • 1
  • 4
  • 15
  • Read the cdll documentation. "By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object." `cv::dnn::Net` is a C++ class. Python has no idea how to work with those. – n. m. could be an AI Nov 10 '20 at 07:48
  • [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/questions/58610333/c-function-called-from-python-via-ctypes-returns-incorrect-value/58611011#58611011). At least. – CristiFati Nov 11 '20 at 00:40

0 Answers0