So, being a Linux guy I stumbled into something pretty puzzling on Windows that I just can't explain.
I have a project structure analougus to this example:
D:\PROJECT
|
| tolkien.py
| __init__.py
|
\---MiddleEarth
| gondor.py
| isengrad.c
| __init__.py
|
\---lib
isengrad.so
Problem: I compile isengrad.c into the shared libary isengrad.so, then load it in gondor.py. My aim is to import gondor.py into tolkien.py.
While gondor.py runs flawlessly when it is run directly, when I import it, the code exits at the point when I load the shared library via ctypes.CDLL, without any error messages.
Reproduction: The content of the files (added some "status messages" to follow where the problem happens):
isengrad.c:
int isengrad(int hobbit){
return hobbit/2;
}
This is then compiled to isengrad.so with
D:\project>chdir MiddleEarth
D:\project\MiddleEarth>gcc -fPIC -shared -o lib/isengrad.so isengrad.c
The shared library is then accessed in gondor.py:
print("started gondor")
import os, ctypes
path_to_isengrad = "D:/project/MiddleEarth/lib/isengrad.so"
print("gondor loads isengrad")
gondor = ctypes.CDLL(path_to_isengrad) # <--- crashes here when imported, not when ran directly
print("gondor loaded isengrad")
gondor.isengrad.argtypes = (ctypes.c_int,)
def faramir(hobbit):
catched_hobbits = gondor.isengrad(hobbit)
return catched_hobbits
if __name__ == '__main__':
print(faramir(5))
print("gondor ran")
print("gondor finished")
which is then imported in tolkien.py:
print("started tolkien")
from MiddleEarth import gondor
print("tolkien imported gondor")
got = gondor.faramir(4)
print(got)
print("tolkien worked")
Now check what happens when I use gondor.py directly VS when I import it in tolkien.py:
D:\project>python MiddleEarth/gondor.py
started gondor
gondor loads isengrad
gondor loaded isengrad
2
gondor ran
gondor finished
D:\project>python tolkien.py
started tolkien
started gondor
gondor loads isengrad
D:\project>
Directly running it causes no problem at all. But importing it causes the whole thing to crash without any word and traceback when loading the shared library. How is this even happening? I even hard-coded the path to the shared library, so different working directory shouldn't be a problem... I didn't have any problem with the very same project on Kubuntu, so this is probably some Windows-related stuff.
Environment:
- Python:
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 - OS:
Windows 10 10.0.17134 Build 17134(installed on C:) - GCC: Installed via Cygwin, version 7.4.0
- Please ask if any other details needed.