首页 > 解决方案 > 致命的 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模式下工作或用解释器启动文件

标签: pythonc++visual-studiovisual-studio-2019python-module

解决方案


推荐阅读