tobook
tobook

Reputation: 93

SWIG syntax error in C struct declaration

I am trying to wrap the following header using SWIG Python, and I get the error:

Error: Syntax error in input(1).

This error, at least according to the build statement, happens at the struct complex declaration.

#ifndef _RMATH_H
#define _RMATH_H

#ifndef _COMPLEX
struct complex {  // error happens here 
    float x,y;
};
#define cabs(a) sqrt((a.x*a.x)+(a.y*a.y))
#endif

#endif

I know SWIG is not compatible with some C variables; what is wrong with this one?

Upvotes: 2

Views: 742

Answers (1)

softwariness
softwariness

Reputation: 4052

The problem is SWIG's handling of the identifier complex.

SWIG does not invoke an external C compiler to parse header files; it has its own parser for C and C++. C99 introduces support for complex numbers. SWIG is attempting to support C complex numbers, but is treating complex as a keyword, which is different from how complex is treated in C (where it is a macro defined in complex.h).

In the depths of SWIG's implementation, it can be seen that this handling of complex as a keyword by the SWIG parser applies only in C mode, not in C++ mode (note the cparse_cplusplus variable being checked):

  if (!cparse_cplusplus && (strcmp(c, "float complex") == 0))
    return T_FLTCPLX;
  if (!cparse_cplusplus && (strcmp(c, "double complex") == 0))
    return T_DBLCPLX;
  if (!cparse_cplusplus && (strcmp(c, "complex") == 0))
    return T_COMPLEX;

And this header is indeed accepted by SWIG when run with the -c++ parameter.

If building as C++ isn't an option, you could rename your struct to something else (e.g. Complex).

If the header definitions aren't under your control, you could take a sledgehammer approach with the pre-processor, by #define-ing complex to an acceptable alternative name instead, e.g. putting the following in your SWIG module interface .i file:

#define complex Complex
%include "rmath.h" // Or whatever your header is called

When you're building the generated SWIG C wrapper file, you'll also need to have the same #define present before rmath.h is included.

Upvotes: 2

Related Questions