0

How to use the Python C-API for the Complex class (documented here) to:

  1. convert a general PyObject (which might be a String, Long, Float, Complex) into a Complex PyObject?
  2. convert a Complex PyObject into String PyObject?

Python has a complex() function, documented here):

Return a complex number with the value real + imag*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion function like int(), long() and float(). If both arguments are omitted, returns 0j.

However, it isn't obvious which API function (if any) is backing it.

It would appear none of them, is the above paragraph talks about two PyObject* parameters, and none of the API functions listed match that signature.

P i
  • 29,020
  • 36
  • 159
  • 267

1 Answers1

1

When in doubt, do what Python does: call the constructor.

PyObject *c1 = PyObject_CallFunction(PyComplex_Type, "s", "1+2j");
If (!c1)
  return NULL;
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Thanks for [PyObject_CallFunction](https://docs.python.org/3/c-api/object.html#c.PyObject_CallFunction), this way of using the API opens up some interesting possibilities! Is there any way of converting an arbitrary PyObject* to a complex type? – P i Dec 12 '14 at 06:08
  • 1
    @Pi: You probably want [`PyObject_CallFunctionObjArgs()`](https://docs.python.org/3/c-api/object.html#c.PyObject_CallFunctionObjArgs) for that. – Ignacio Vazquez-Abrams Dec 12 '14 at 06:15
  • I notice PyComplex_Type is a PyTypeObject, whereas signatures specify a PyObject*. Wouldn't I need reinterpret_cast(&PyTypeObject) or something similarly nasty? – P i Dec 12 '14 at 06:38
  • 1
    @Pi: ["Type objects can be handled using any of the `PyObject_*()` [...\] functions"](https://docs.python.org/3/c-api/typeobj.html) So some sort of casting may be required, but it shouldn't kill the interpreter. – Ignacio Vazquez-Abrams Dec 12 '14 at 06:48