5

I'm new to the Python C-API.

Currently I get objects from the embedded Python module via

PyObject* a = (PyObject*) PyObject_GetAttrString(pModule, "a");
std::cout << "a as long is " << PyLong_AsLong(a) << std::endl;

I access numpy objects via

PyArrayObject* array = (PyArrayObject*) PyObject_GetAttrString(pModule, "A");

How can I test if the object is a really a PyArrayObject? In other words how to do what I would do in Python via isinstance(a, numpy.ndarray)?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Fabian
  • 107
  • 1
  • 5

1 Answers1

7

Use PyArray_Check or PyArray_CheckExact. Use PyArray_Check if subclasses are okay, or PyArray_CheckExact if you need an object with type exactly numpy.ndarray.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • This does not work for me ?! But I need to note, that I'm also not able to allocate a numpy array from C++ side (same code on macOS with clang and Linux with gcc 10). ```std::cout << "check a: " << PyArray_Check(a) << std::endl; ``` results in `isinstance : unknown location:0: fatal error: in embedded_python: memory access violation at address: 0x00000010: no mapping at fault address` – Fabian Oct 09 '20 at 21:35
  • I made a mistake pasting my error: It is `check a: unknown location:0: fatal error: in "embedded_python": memory access violation at address: 0x00000010: no mapping at fault address`- both solutions fail for me?! – Fabian Oct 09 '20 at 21:47
  • That sounds like a new question. Instead of trying to figure that out here in the comments, create a new question about the error. – Warren Weckesser Oct 09 '20 at 23:12