python - 致命的 Python 错误:尝试在 Visual Studio 2019 中调试 C++ python 模块时出现 _PyInterpreterState_GET
问题描述
我有一个 python 模块,由guide用 C++ 编写。该模块本身运行良好,但我无法调试该模块,正如它在指南中所写的那样。Python解释器抛出
Fatal Python error: _PyInterpreterState_GET: the function must be called with the GIL held, but the GIL is released (the current Python thread state is NULL)
Python runtime state: unknown
Python代码:
import cpplib
import os
print(cpplib.fast_tanh(0.123))
os.system('pause')
模块代码:
#include <Python.h>
#include <Windows.h>
#include <cmath>
#include <string>
const double e = 2.7182818284590452353602874713527;
double sinh_impl(double x) {
return (1 - pow(e, (-2 * x))) / (2 * pow(e, -x));
}
double cosh_impl(double x) {
return (1 + pow(e, (-2 * x))) / (2 * pow(e, -x));
}
PyObject* tanh_impl(PyObject* /* unused module reference */, PyObject* o) {
double x = PyFloat_AsDouble(o);
double tanh_x = sinh_impl(x) / cosh_impl(x);
return PyFloat_FromDouble(tanh_x);
}
static PyMethodDef cpplib_methods[] = {
// The first property is the name exposed to Python, fast_tanh
// The second is the C++ function with the implementation
// METH_O means it takes a single PyObject argument
{ "fast_tanh", (PyCFunction)tanh_impl, METH_O, "Fast tanh shit"},
// Terminate the array with an object containing nulls.
{ nullptr, nullptr, 0, nullptr }
};
static PyModuleDef cpplib_module = {
PyModuleDef_HEAD_INIT,
"cpplib", // Module name to use with Python import statements
"Test C++ lib", // Module description
0,
cpplib_methods // Structure that defines the methods of the module
};
PyMODINIT_FUNC PyInit_cpplib() {
return PyModule_Create(&cpplib_module);
}
# setup.py
from setuptools import setup, Extension
sfc_module = Extension('cpplib', sources = ['module.cpp'])
setup(
name='cpplib',
version='1.1',
description='Python Package with superfastcode C++ extension',
ext_modules=[sfc_module]
)
问题是,是什么导致了错误?看起来 VS 调试配置做了一些事情,所以解释器崩溃了。没关系,如果我用调试启动python代码,它无论如何都会崩溃,但是模块在交互式python模式下工作或用解释器启动文件
解决方案
推荐阅读
- laravel - 如何在 Laravel 中正确实现这种多态关系?
- java - 将生产 Android 应用程序从 Windows 7 正确移动/移植到基于 Linux 的系统
- qt - Qt: How to implement simple internal drag&drop for reordering items in QListView using a custom model
- r - xaringan code output same style as bookdown
- agda - 在命令行使用 Agda 2.5.4.2 编译 Hello World 时出错
- java - JVM 线程是否会始终保持其到 OS 线程的映射
- ios - How to upload image in Swift using Moya?
- winforms - SkiaSharp:如何限制或降低大(4K)屏幕的绘图像素分辨率?
- php - 未定义索引但索引存在
- typescript - Typescript 类型中的嵌套三元条件扩展