How can I write a C function that takes either an int or a float?
<p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>

<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only float.</p>

<p>How can I make my function allow inputs that are either ints or floats?</p>

<p>I'm wondering if I should just take the input and put it into a PyObject and somehow take the type of the PyObject - is that the right approach?</p>

<p>Floats are (usually) passed in via registers while ints are (usually) passed in via the stack. This means that you literally cannot, inside the function, check whether the argument is a float or an int.</p>

<p>The only workaround is to use variadic arguments, with the first argument specifying the type as either int or double (not float).</p>

<pre><code>func_int_or_double (uint8_t type, ...) {
va_list ap;
va_start (ap, type);
int intarg;
double doublearg;
if (type==1) {
   intarg = va_arg (ap, int);
}
if (type==2) {
   doublearg = va_arg (ap, double);
}
va_end (ap);
// Your code goes here
}
</code></pre>

<p>Although, I'm not really sure if python can handle calling variadic functions, so YMMV. As a last ditch-effort you can always sprintf the value into a buffer and let your function sscanf float/int from the buffer.</p>

python c python-extensions