P i
P i

Reputation: 30704

How to construct a Complex from a String using Python's C-API?

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.

Upvotes: 1

Views: 175

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798914

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

PyObject *c1 = PyObject_CallFunction(PyComplex_Type, "s", "1+2j");
If (!c1)
  return NULL;

Upvotes: 1

Related Questions