我試圖移植此Python extension以使用Python 3. Python 3對Python C/C++ API做了很多更改,這些更改需要修改傳統模塊的初始化和參數傳遞函數。到目前爲止,我已經把舊的Python 2代碼:Python 3 C擴展導致分段錯誤導入時
#include <Python.h>
#include <openssl/crypto.h>
static PyObject* SecureString_clearmem(PyObject *self, PyObject *str) {
char *buffer;
Py_ssize_t length;
if (PyString_AsStringAndSize(str, &buffer, &length) != -1) {
OPENSSL_cleanse(buffer, length);
}
return Py_BuildValue("");
}
static PyMethodDef SecureStringMethods[] = {
{"clearmem", SecureString_clearmem, METH_O,
PyDoc_STR("clear the memory of the string")},
{NULL, NULL, 0, NULL},
};
PyMODINIT_FUNC initSecureString(void)
{
(void) Py_InitModule("SecureString", SecureStringMethods);
}
而且我做了這一點,以下this example:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <openssl/crypto.h>
static PyObject* SecureString_clearmem(PyObject *self, PyObject *args) {
char *buffer;
Py_ssize_t length;
if(!PyArg_ParseTuple(args, "s#", &buffer, &length)) {
return NULL;
}
OPENSSL_cleanse(buffer, length);
Py_RETURN_NONE;
}
static PyMethodDef SecureStringMethods[] = {
{"SecureString_clearmem", SecureString_clearmem, METH_VARARGS, "clear the memory of the string"},
{NULL, NULL, 0, NULL},
};
static struct PyMethodDef SecureStringDef = {
PyModuleDef_HEAD_INIT,
"SecureString",
NULL,
-1,
SecureStringMethods,
};
PyMODINIT_FUNC PyInit_SecureString(void) {
Py_Initialize();
return PyModule_Create(&SecureStringDef);
}
從理論上講,這應該遵循新的Python模塊初始化3條規則,參數傳遞和字符串大小變量。它成功地編譯和安裝(我用與項目分佈在同一setup.py),但是當我嘗試將其導入:
import SecureString
我得到一個分段錯誤:
Segmentation fault: 11
我有試圖附加gdb來檢查C代碼,但gdb不能在我的電腦上使用Python C模塊工作。我也試着評論OpenSSL代碼,看看這是否是問題的根源,但無濟於事。我的Python3安裝運行其他不使用這個庫的程序。有人可以看看這個,並建議我應該看看或我應該嘗試下一步?
謝謝!
感謝這個提示!順便說一下,我在我的問題中添加了一個概述/摘要,試圖儘可能清楚和描述,以幫助人們稍後再看這個問題。這是否在這裏皺眉? – SquawkBirdies
你的問題是完全正確的@SquawkBirdies。在這個問題上,seg故障仍然出現? –
實施了建議並且段錯誤消失了。初步測試看起來顯示預期的行爲。謝謝! – SquawkBirdies