使用ctypes.CDLL加载C++编译的共享DLL文件失败求助
使用ctypes.CDLL加载C++编译的共享DLL文件失败求助
我在C程序里写了一些函数,编译成.dll文件后想在Python中调用以提升性能。这个.dll在其他C程序里能正常工作,但用Python加载时却抛出了错误:
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.
我反复检查了路径,甚至用了绝对路径,但都没用。我已经折腾了一整天,用各种方式重新编译.dll,但问题依旧——所有编译出来的.dll在C++里都能正常工作,就是Python不行。
我的DLL编译命令:
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) { ... } }
最后是我的Python脚本:
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
有没有人能帮我解决这个问题?
备注:内容来源于stack exchange,提问作者user26649650
相关产品推荐
相关产品推荐

