Skip to content
Snippets Groups Projects
Commit fd25501a authored by AlQuemist's avatar AlQuemist
Browse files

SWIG: introduce a typemap to use Python sequences instead of R3

parent eae34820
No related branches found
No related tags found
1 merge request!2766Accept a Python sequence instead of an R3 instance
// typemap R3 to accept a Python R3 instance or a Python sequence
%ignore BA_SWIG_getArg_R3;
%inline
%{
// convert a given Python R3 instance or a Python sequence to a C++ R3 instance
int BA_SWIG_getArg_R3(PyObject* input, swig_type_info* pTypeInfo,
void*& r3_ptr, R3& r3_tmp)
{
// if the input is already an R3 instance, merely extract the pointer
int res = SWIG_ConvertPtr(input, &r3_ptr, pTypeInfo, 0);
if (SWIG_IsOK(res)) {
return 1;
} else if (PySequence_Check(input) && PySequence_Size(input) == 3) {
// check if the input is a Python sequence of length 3
// extract the elements
PyObject *x = PySequence_GetItem(input, 0);
PyObject *y = PySequence_GetItem(input, 1);
PyObject *z = PySequence_GetItem(input, 2);
// check that all elements of the Python sequence are numbers
if (!(PyNumber_Check(x) && PyNumber_Check(y) && PyNumber_Check(z))) {
Py_XDECREF(x);
Py_XDECREF(y);
Py_XDECREF(z);
return -1;
}
r3_tmp = R3(PyFloat_AsDouble(x), PyFloat_AsDouble(y), PyFloat_AsDouble(z));
Py_XDECREF(x);
Py_XDECREF(y);
Py_XDECREF(z);
return 2;
} else {
return -2;
}
}
%}
// SWIG typemap for input: Python iterable/R3 instance to R3&
// NOTE: Mapping a non-const R3 argument should be avoided, since in that case,
// the caller might expect that the input argument be modified,
// and with Python sequences (used in place of R3), this modification is not performed.
// NOTE: This method works only for functions or methods which are not overloaded.
// Overloaded functions or methods must be explicitly 'extended' to accept a
// Python sequence instead of an R3 instance.
%typemap(in) const R3& (R3 tmpR3) {
// if the input is already an R3 instance, merely extract the pointer
void* argp = 0;
swig_type_info* pTypeInfo_R3_ref = SWIG_TypeQuery("R3&");
const int res = BA_SWIG_getArg_R3($input, pTypeInfo_R3_ref, argp, tmpR3);
switch(res) {
case 1:
$1 = reinterpret_cast<R3*>(argp);
break;
case 2:
$1 = &tmpR3;
break;
case -1:
PyErr_SetString(PyExc_TypeError, "R3: Python sequence elements must be numbers");
SWIG_fail;
break;
default:
PyErr_SetString(PyExc_TypeError, "R3: expected an R3 instance or a Python sequence of 3 numbers");
SWIG_fail;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment