6

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)?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
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?!
That sounds like a new question. Instead of trying to figure that out here in the comments, create a new question about the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.