Skip to content
Advertisement

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

this is my test.cpp file.(I also used makefile to create dll file)

//#include <iostream>

int foo(int a)
{
    if (a > 1)
        return a + 1;
    else
        return a + 2;
}

when I run following code in python

import os 
import ctypes

lib_bfs = ctypes.WinDLL("D:\advanced_programming\HW7\cpp_part\libtest.dll")
print(lib_bfs)

everything is ok and I get this output from python.

<CDLL 'D:advanced_programmingHW7cpp_partlibtest.dll', handle 69d00000 at 0x2b7677e6400>

but when I change my test.cpp in this way(I just uncommented iostream):

#include <iostream>

int foo(int a)
{
    if (a > 1)
        return a + 1;
    else
        return a + 2;
}

I get the following error from 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:usersaliappdatalocalprogramspythonpython38libctypes__init__.py", line 373, in __init__
    self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'D:advanced_programmingHW7cpp_partlibtest.dll' (or one of its dependencies). Try using the full path with constructor syntax.

this is also my dependencies enter image description here

by the way I have to mention that when I use Linux, everything is just fine.(I just used .so files) but there might be some problem with windows

I appreciate your help.

Advertisement

Answer

thanks to @DhirajWishal first I added the following line in my makefile.

g++ -std=c++17   -O3  -I./h -g -fPIC -shared ./cpp/test.cpp -o ./libtest.dll -static-libgcc -static-libstdc++

then I placed libwindpthread-1.dll (which was in F:/strawberry/c/bin/ dir ) next to my makefile and the problem was solved.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement