[Python] Python: ctypes.CDLL cannot load c++ compiled shared .dll file

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have written some functions within my C++ app and i compiled it to use it as .dll and so i can use those functions in python for a better performance. The .dll file works fine when i'm using it for another C++ application but when i want to load it in my python program it throws this error:

    Traceback (most recent call last):
    File "e:\My Apps\Python\Telegram_Bots\Calculator\main.py", line 6, in <module>
    lib = CDLL("E:\My Apps\Python\Telegram_Bots\Calculator\lib.dll")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "c:\Users\KHATAM_PC\AppData\Local\Programs\Python\Python311\Lib\ctypes\__init__.py", line 376, in __init__
    self._handle = _dlopen(self._name, mode)
    ^^^^^^^^^^^^^^^^^^^^^^^^^
    FileNotFoundError: Could not find module 'E:\My Apps\Python\Telegram_Bots\Calculator\lib.dll' (or one of its dependencies). Try using the full path with constructor syntax.


    I've quarterable checked the path and even used the full-path, never worked, been trying for a whole day, compiling the .dll again and again in different ways and methods but nothing came out of them, all of them yet worked in C++

    .dll exportation command: g++ -DMATH_DLL_EXPORTS -shared -std=c++17 -o lib.dll lib.cpp

    lib.hpp:

    // #pragma once

    #ifndef MATH_DLL_API
    #define MATH_DLL_API

    #ifdef _WIN32
    #define DLL_EXPORT __declspec(dllexport)
    #else
    #define DLL_EXPORT
    #endif

    #include <iostream>
    #include <vector>
    extern "C" {
    DLL_EXPORT int precedence(char o);
    DLL_EXPORT float calc(float a, float b, char o);
    DLL_EXPORT void calculate(std::vector<float>& values, std::vector<char>& ops);
    DLL_EXPORT float evaluate(std::string e);
    }
    #endif // MATH_DLL_API


    lib.cpp:

    #include "lib.hpp"
    #include <iostream>
    #include <vector>
    extern "C" {
    DLL_EXPORT int precedence(char o) { ... }
    DLL_EXPORT float calc(float a, float b, char o) { ... }
    DLL_EXPORT void calculate(std::vector<float>& values, std::vector<char>& ops) { ... }
    DLL_EXPORT float evaluate(std::string e) { ... }
    }


    And finaly, the python script:

    from ctypes import c_char, c_int, c_float, c_char_p, c_void_p, CDLL, cdll, POINTER

    lib = CDLL("E:\My Apps\Python\Telegram_Bots\Calculator\lib.dll")

    lib.evaluate.argtypes = [c_char_p]
    lib.evaluate.restype = c_float

    lib.calculate.argtypes = [POINTER(c_float), POINTER(c_char)]
    lib.calculate.restype = c_void_p

    lib.calc.argtypes = [c_float, c_float, c_char]
    lib.calc.restype = c_float

    lib.precedence.argtypes = [c_char]
    lib.precedence.restype = c_int


    Can anybody help please?

    Continue reading...

Compartilhe esta Página