You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++调用含Numpy的Python函数报错:ImportError: cannot import name _remove_dead_weakref

Fixing "ImportError: cannot import name _remove_dead_weakref" When Calling Numpy-Using Python Functions from C++

Let's break down why you're hitting this error and how to fix it:

Root Cause

This error almost always comes down to version incompatibility between Python 2.7 and numpy, or missing proper initialization of the Python environment in your C++ code. Python 2.7 only supports numpy versions up to 1.16.6—any newer numpy release will try to access functions that don't exist in Python 2.7's standard library. Additionally, if you don't explicitly set up the Python path in your C++ code, numpy might not be discovered or initialized correctly.

Step-by-Step Solutions

  1. Downgrade numpy to a Python 2.7-compatible version
    First, replace any incompatible numpy installation with the last official release that supports Python 2.7. Run this command:

    pip2 install numpy==1.16.6 --force-reinstall
    

    This ensures numpy won't try to call unsupported functions from Python 2.7.

  2. Properly Initialize the Python Environment in C++
    Your existing code likely only calls Py_Initialize(), but you need to explicitly set the Python path to make numpy and your custom module discoverable. Here's an updated code example:

    #include <Python.h>
    #include <stdio.h>
    
    int main() {
        // Initialize the Python interpreter
        Py_Initialize();
    
        // Set Python path to include numpy's site-packages and your script directory
        // Replace the paths below with your actual system paths for Python 2.7
        const char* python_path = "/usr/lib/python2.7/site-packages:/path/to/your/python/scripts";
        PySys_SetPath(python_path);
    
        // Import your Python module that uses numpy
        PyObject* module = PyImport_ImportModule("your_numpy_module");
        if (!module) {
            PyErr_Print();
            return 1;
        }
    
        // Get the target function from the module
        PyObject* func = PyObject_GetAttrString(module, "your_numpy_function");
        if (!func || !PyCallable_Check(func)) {
            PyErr_Print();
            return 1;
        }
    
        // Prepare arguments and call the function
        PyObject* args = PyTuple_New(2);
        PyTuple_SetItem(args, 0, PyFloat_FromDouble(5.0));
        PyTuple_SetItem(args, 1, PyFloat_FromDouble(10.0));
        PyObject* result = PyObject_CallObject(func, args);
    
        if (result) {
            double output = PyFloat_AsDouble(result);
            printf("Function result: %.2f\n", output);
            Py_DECREF(result);
        } else {
            PyErr_Print();
        }
    
        // Clean up Python objects to avoid leaks
        Py_DECREF(args);
        Py_DECREF(func);
        Py_DECREF(module);
        Py_Finalize();
    
        return 0;
    }
    
  3. Verify Your Compilation Command
    Keep using your existing compile command, but double-check that the Python 2.7 headers and library are correctly referenced:

    g++ test.cpp -I/usr/include/python2.7 -lpython2.7 -o test_numpy_call
    

    If you installed numpy via pip2, use pip2 show numpy | grep Location to find the correct site-packages path for the C++ code.

Bonus: A Quick Note About Python 2.7

Python 2.7 reached end-of-life in 2020, so if possible, consider migrating your code to Python 3 (which has full, active numpy support). But if you're stuck on Python 2.7 for legacy reasons, the above steps should resolve your error.

内容的提问来源于stack exchange,提问作者Steven T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:55:02