Python 访问 .exe 导出函数时发生 ctypes 访问冲突
Python ctypes access violation when accessing an .exe exported function
在 python 上通过 ctypes 调用导出的 c++ 函数时出现访问冲突。
我将问题缩小到以下 c++ 函数:(在 vs2017 上编译)
#include <cstdio>
__declspec(dllexport) void x()
{
FILE* out = stdout; // After debugging, this is where the access violation happens.
}
调用该函数时出现以下错误(使用 vs 调试时显示的错误相同):
Python代码:
ctypes.windll.<exe_name>.x()
错误:
OSError: exception: access violation writing 0x_some_address
关键是,上面是编译成EXE的。
(当我导出调用 'main' 入口点的函数时,整个事情开始了)
在这方面花了一些时间并尝试了所有方法之后,我尝试将上面的代码编译为 DLL,现在它按预期工作了。
所以问题是,有人可以向我解释导致问题的原因吗?
我知道(或多或少)内存管理差异,但不了解细节。
谢谢。
这篇文章似乎提供了足够的背景信息和可能的解决方案:
https://www.codeproject.com/Articles/1045674/Load-EXE-as-DLL-Mission-Possible
将 EXE 作为 DLL 加载的主要区别是:
- The CRT is not initialized, including any global variables, and
- The Import Address Table is not correctly configured, which means that all calls to imported functions will crash.
在 python 上通过 ctypes 调用导出的 c++ 函数时出现访问冲突。
我将问题缩小到以下 c++ 函数:(在 vs2017 上编译)
#include <cstdio>
__declspec(dllexport) void x()
{
FILE* out = stdout; // After debugging, this is where the access violation happens.
}
调用该函数时出现以下错误(使用 vs 调试时显示的错误相同):
Python代码:
ctypes.windll.<exe_name>.x()
错误:
OSError: exception: access violation writing 0x_some_address
关键是,上面是编译成EXE的。
(当我导出调用 'main' 入口点的函数时,整个事情开始了)
在这方面花了一些时间并尝试了所有方法之后,我尝试将上面的代码编译为 DLL,现在它按预期工作了。
所以问题是,有人可以向我解释导致问题的原因吗?
我知道(或多或少)内存管理差异,但不了解细节。
谢谢。
这篇文章似乎提供了足够的背景信息和可能的解决方案: https://www.codeproject.com/Articles/1045674/Load-EXE-as-DLL-Mission-Possible
将 EXE 作为 DLL 加载的主要区别是:
- The CRT is not initialized, including any global variables, and
- The Import Address Table is not correctly configured, which means that all calls to imported functions will crash.