Python C语言应用程序API sys.getsizeof()

km0tfn4u  于 2023-02-15  发布在  Python
关注(0)|答案(1)|浏览(109)

我正在尝试调用Python的C库中的getsizeof方法,下面是我的代码:

//Returns in bytes the size of obj in memory
//sys.getsizeof(obj)
size_t getSizeOf(PyObject* obj){ //obj could be dict or list
    Py_INCREF(obj);

    PyObject* sys = PyModule_New("sys"); //import sys

    PyObject* string = Py_BuildValue("s", "getsizeof");

    PyObject* res = PyObject_CallMethodObjArgs(sys, string, obj, NULL); //res = sys.getsizeof(obj)
    Py_DECREF(sys);
    Py_DECREF(string);

    long tmp = PyLong_AsLong(res);
    Py_DECREF(res);

    Py_DECREF(obj);
    return (size_t)tmp;
}

这个代码给了我一个segfault。不知道为什么。我做错了什么?

bkhjykvo

bkhjykvo1#

使用PyImport_ImportModule导入一个模块。使用PyObject_CallMethod也简化了调用。不需要增加传入的obj

#include <Python.h>

__declspec(dllexport)  // For Windows
size_t getSizeOf(PyObject* obj) {
    PyObject* sys = PyImport_ImportModule("sys");
    PyObject* res = PyObject_CallMethod(sys, "getsizeof", "O", obj);
    Py_DECREF(sys);
    long tmp = PyLong_AsLong(res);
    Py_DECREF(res);
    return (size_t)tmp;
}

从Python调用方法:

>>> import ctypes as ct
>>> dll = ct.PyDLL('./test')
>>> x=[1,2,3]
>>> dll.getSizeOf.argtypes = ct.py_object,
>>> dll.getSizeOf.restype = ct.c_size_t
>>> dll.getSizeOf(x)
88
>>> import sys
>>> sys.getsizeof(x) # to verify
88

相关问题