'Problem creating dll and loading then in Python ctypes

I want to learn to create DLLs in c++ and use them in python to increase the speed of calculations. To begin with, I tried to create a simple C++ dll and load it in Python using ctypes, but I get OSError: [WinError 126]:

Traceback (most recent call last): 
File "C:/Users/unknown/Documents/Work_Pyth/tests/test.py", line 4, in <module> lib = CDLL("tdll.dll") File "C:\Program Files (x86)\Python36\lib\ctypes_init_.py", line 348, in init self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module was not found 

DLL code main.h

#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
#define DLL_EXPORT __declspec(dllexport)
extern "C" void DLL_EXPORT fun(double* in,long len);
#endif

DLL code main.cpp

#include "main.h"
double * v;
extern "C" void DLL_EXPORT fun(double* in,long len)
{
    v=new double[len];
    for (long ii=0; ii<len; ii+=1){
        v[ii]=ii;
    }
    for (long ii=0; ii<len; ii+=1){
        in[ii]=v[ii];
    }
    delete v;
}
extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    return TRUE;
}

In real code the DLL will need to use temporary arrays, so the test DLL contains an intermediate array v. I compile DLL using CodeBlocks with mingw:

-------------- Build: Release in tdll (compiler: GNU GCC Compiler)---------------

g++.exe -fPIC -O -Wall -fPIC -DBUILD_DLL -O -fPIC  -c C:\Users\unknown\Documents\Work_Cpp\tdll\main.cpp -o obj\Release\main.o

How do i use the DLL, Python code

from ctypes import *
import numpy as np

lib = CDLL("tdll.dll")
len=5
v=np.zeros(len)
print(v)
lib.fun.restype=c_void_p
lib.fun.argtypes=(np.ctypeslib.ndpointer(dtype=np.float64),  c_long)
lib.fun(v,len)
print(v)

Why does the error OSError: [WinError 126] occur? I don't think it can be caused by dependencies. Is it possible to use new and delete operators in DLL code? Thanks for any help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source