![](/img/trans.png)
[英]Debugging Python C++ extension from Visual Studio Code on Linux
[英]Debugging C++ extension for Python
嘗試調試Python的C ++擴展時遇到問題。 錯誤是
致命的Python錯誤:PyThreadState_Get:當前沒有線程
我遵循了本指南,並且在發行版中運行時可以使用。
Python代碼:
from itertools import islice
from random import random
from time import perf_counter
COUNT = 500000 # Change this value depending on the speed of your computer
DATA = list(islice(iter(lambda: (random() - 0.5) * 3.0, None), COUNT))
e = 2.7182818284590452353602874713527
def sinh(x):
return (1 - (e ** (-2 * x))) / (2 * (e ** -x))
def cosh(x):
return (1 + (e ** (-2 * x))) / (2 * (e ** -x))
def tanh(x):
tanh_x = sinh(x) / cosh(x)
return tanh_x
def sequence_tanh(data):
'''Applies the hyperbolic tangent function to map all values in
the sequence to a value between -1.0 and 1.0.
'''
result = []
for x in data:
result.append(tanh(x))
return result
def test(fn, name):
start = perf_counter()
result = fn(DATA)
duration = perf_counter() - start
print('{} took {:.3f} seconds\n\n'.format(name, duration))
for d in result:
assert -1 <= d <=1, " incorrect values"
from superfastcode import fast_tanh
if __name__ == "__main__":
test(lambda d: [fast_tanh(x) for x in d], '[fast_tanh(x) for x in d]')
C ++代碼:
#include <Python.h>
#include <cmath>
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 *, PyObject* o) {
double x = PyFloat_AsDouble(o);
double tanh_x = sinh_impl(x) / cosh_impl(x);
return PyFloat_FromDouble(tanh_x);
}
static PyMethodDef superfastcode_methods[] = {
// The first property is the name exposed to Python, fast_tanh, the second is the C++
// function name that contains the implementation.
{ "fast_tanh", (PyCFunction)tanh_impl, METH_O, nullptr },
// Terminate the array with an object containing nulls.
{ nullptr, nullptr, 0, nullptr }
};
static PyModuleDef superfastcode_module = {
PyModuleDef_HEAD_INIT,
"superfastcode", // Module name to use with Python import statements
"Provides some functions, but faster", // Module description
0,
superfastcode_methods // Structure that defines the methods of the module
};
PyMODINIT_FUNC PyInit_superfastcode() {
return PyModule_Create(&superfastcode_module);
}
我正在使用Python 3.6的64位版本,並正在x64模式下構建C ++代碼。 Visual Studio 2017 15.6.4
我正在鏈接C:\\ Python \\ Python36.x64 \\ libs \\ python36_d.lib並包含C:\\ Python \\ Python36.x64 \\ include中的頭文件
我的Python解釋器位於C:\\ Python \\ Python36.x64 \\
運行發布版本時得到此結果
[fast_tanh(x) for x in d] took 0.067 seconds
更新 :我讓它在Py x86而不是x64上運行。 當我到達斷點並越過(F10)時,它將引發異常。
我從Microsoft的Steve Dower獲得了此解決方案:
這看起來更像是調試二進制文件和發行標頭之間的不匹配。
您參考的指南旨在始終使用Python的發行版二進制文件,即使您正在構建調試擴展。 因此,要么應該鏈接到python36.lib / python36.dll,要么忽略指南中列出的大多數設置更改,然后鏈接到python36_d.lib / python36_d.dll(一旦設置了路徑,鏈接應該是自動的-選擇C運行時庫的確定將確定是否使用調試/發布Python)。
參考: PTVS問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.