如何正确编写 python 的 C++ DLL 文件?

how to write C++ DLL file for python correctly?

这是我的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/ 目录中)放在我的 makefile 旁边,问题就解决了。