如何解决如何正确为python编写C++ DLL文件?
这是我的 test.cpp 文件。(我也用 makefile 创建了 dll 文件)
//#include <iostream>
int foo(int a)
{
if (a > 1)
return a + 1;
else
return a + 2;
}
当我在 python 中运行以下代码时
import os
import ctypes
lib_bfs = ctypes.WinDLL("D:\\advanced_programming\\HW7\\cpp_part\\libtest.dll")
print(lib_bfs)
一切正常,我从 python 得到这个输出。
<CDLL 'D:\advanced_programming\HW7\cpp_part\libtest.dll',handle 69d00000 at 0x2b7677e6400>
但是当我以这种方式更改我的 test.cpp 时(我只是取消了 iostream 的注释):
#include <iostream>
int foo(int a)
{
if (a > 1)
return a + 1;
else
return a + 2;
}
我从 python 中收到以下错误。
Traceback (most recent call last):
File "d:/advanced_programming/HW7/cpp_part/connector.py",line 4,in <module>
lib_bfs = ctypes.WinDLL("D:\\advanced_programming\\HW7\\cpp_part\\libtest.dll")
File "c:\users\ali\appdata\local\programs\python\python38\lib\ctypes\__init__.py",line 373,in __init__
self._handle = _dlopen(self._name,mode)
FileNotFoundError: Could not find module 'D:\advanced_programming\HW7\cpp_part\libtest.dll' (or one of its dependencies). Try using the full path with constructor syntax.
这也是我的依赖 enter image description here
顺便提一下,当我使用 Linux 时,一切都很好。(我只是使用了 .so 文件)但 Windows 可能存在一些问题
感谢您的帮助。
解决方法
感谢@DhirajWishal 首先,我在我的 makefile 中添加了以下行。
g++ -std=c++17 -O3 -I./h -g -fPIC -shared ./cpp/test.cpp -o ./libtest.dll -static-libgcc -static-libstdc++
然后我将 libwindpthread-1.dll
(在 F:/strawberry/c/bin/
dir 中)放在我的 makefile 旁边,问题就解决了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。