Question

I'm just playing around SWIG to make python' module for specific C library. I got the trouble with double and float variables. Here an example:

/***** simple.c *****/
#include <stdio.h>
double doublefun(double b){
        printf("c(%g)",b);
        return b+12.5;
}

float floatfun(float b){
        printf("c(%f)",b);
        return b+12.5;
}

int intfun(int b){
        printf("c(%d)",b);
        return b+12;
}

/***** simple.i *****/
%module simple
%{
%}

extern double doublefun(double);
extern float floatfun(float);
extern int intfun(int);

AND

#***** simpletest.py *****#
import simple

print "i:",simple.intfun(2)
print "f:",simple.floatfun(2.3)
print "d:",simple.doublefun(2.3)

The result is:

i:c(2) 14
f:c(36893488147419103232.000000) 30.0
d:c(2.3) 6.0

Any ideas why it happens?

P.S. If I call functions from C code ....

int main(int argc, char** argv){
        printf("i::%d\n",intfun(2));
        printf("f::%f\n",floatfun(2.3));
        printf("d::%g\n",doublefun(2.3));
        return 0;
}

Everything is fine:

c(2)i::14
c(2.300000)f::14.800000
c(2.3)d::14.8
Was it helpful?

Solution

If you add the header as shown in the first example in the docs:

%{
#include "simple.h"
%}

then you should get:

i:c(2) 14
f:c(2.300000) 14.8000001907
d:c(2.3) 14.8

See full example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top