Reputation: 148
I'm trying to call a method getsizeof from a C library for Python. Here's my code:
//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;
}
And this code gives me a segfault. No clue why. What am I doing wrong?
Upvotes: 2
Views: 105
Reputation: 177715
Use PyImport_ImportModule
to import a module. Also using PyObject_CallMethod
simplifies the call. Incrementing the incoming obj
is not needed.
#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;
}
Calling method from 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
Upvotes: 3