3

I read the documentation on NumPy C API I could find, but still wasn't able to find out whether there is a possibility to construct a matrix object with C API — not a two-dimensional array. The function is intended for work with math matrices, and I don't want strange results if the user calls matrix multiplication forgetting to convert this value from an array to a matrix (multiplication and exponentiation being the only difference that matrix subclass has).

2 Answers2

6

You can call any python callable with the PyObject_Call* functions.

PyObject *numpy = PyImport_ImportModule("numpy");
PyObject *numpy_matrix = PyObject_GetAttrString(numpy, "matrix");
PyObject *my_matrix = PyObject_CallFunction(numpy_matrix, "(s)", "0 0; 0 0");

This will create a matrix my_matrix of size 2x2.

EDIT: Changed references to numpy.zeros/numpy.ndarray to numpy.matrix instead.

I also found a good tutorial on the subject: http://starship.python.net/crew/hinsen/NumPyExtensions.html

Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
3

numpy.matrix is an ordinary class defined in numpy/core/defmatrix.py. You can construct it using C API as any other instance of user-defined class in Python.

jfs
  • 399,953
  • 195
  • 994
  • 1,670