test.py
from ctypes import *
from random import randint
tester = cdll.LoadLibrary('./test.dll')
print(tester.test(randint(1, 100)))
test.cpp
#include
int cppTest(int num) {
std::vector v;
v.push_back(num);
return v.back();
}
extern "C" __declspec(dllexport) int test(int num) {
return cppTest(num);
}
Затем выполните следующие команды:
> g++ -o test.dll -shared -fPIC test.cpp
> python test.py
И я получил следующую ошибку:
Traceback (most recent call last):
File "test.py", line 4, in
tester = cdll.LoadLibrary('./test.dll')
File "D:\Programs\Python\Python38\lib\ctypes\__init__.py", line 451, in LoadLibrary
return self._dlltype(name)
File "D:\Programs\Python\Python38\lib\ctypes\__init__.py", line 373, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 1114] Dynamic-link library (DLL) initialization routine failed.
Я думал, что использование любой из библиотек STL C++ вызовет проблему, поэтому я попробовал использовать новый int, и та же ошибка возникла снова.
Моя среда:
- Windows 10 x64
- Python 3.8.5 x64 (та же проблема с Python 3.6)
- TDM-GCC 9.2.0
РЕДАКТИРОВАТЬ:
Скомпилированный файл dll является 64-разрядным, что проверяется запуском следующей команды в VS 2017:
E:\...\test>dumpbin /headers test.dll
Microsoft (R) COFF/PE Dumper Version 14.16.27044.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file test.dll
PE signature found
File Type: DLL
FILE HEADER VALUES
8664 machine (x64)
13 number of sections
612A415D time date stamp Sat Aug 28 21:59:57 2021
10B000 file pointer to symbol table
6FA9 number of symbols
F0 size of optional header
2026 characteristics
Executable
Line numbers stripped
Application can handle large (>2GB) addresses
DLL
РЕДАКТИРОВАТЬ 2:
Когда я попытался использовать MinGW в качестве компилятора, снова возникла ошибка:
E:\...\test>python test.py
Traceback (most recent call last):
File "test.py", line 4, in
tester = cdll.LoadLibrary('./test.dll')
File "D:\Programs\Python\Python38\lib\ctypes\__init__.py", line 451, in LoadLibrary
return self._dlltype(name)
File "D:\Programs\Python\Python38\lib\ctypes\__init__.py", line 373, in __init__
self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'E:\...\test\test.dll' (or one of its dependencies). Try using the full path with constructor syntax.
Подробнее здесь: https://stackoverflow.com/questions/689 ... ialization