472,364 Members | 1,789 Online

# swig: conversion of C double to Python float

Hi,

I am learning swig to use C codes from Python.

Here is the swig file mvf.i:
%module mvf
%include "carrays.i"
%array_class(double, doubleArray);
%typemap(out) double, float "\$result = PyFloat_FromDouble(\$1);"
%include mvf.h

Here is the mvf.c file
#include <stdio.h>
double SumSquares(int n, double x[])
{
double sum;
int i;
for (sum = 0.0, i = 0; i < n; i++) sum += x[i]*x[i];
printf("DEBUG: %f\n", sum);
return sum;
}

The mvf.h file has the single line:
double SumSquares(int n, double x[]);

Here is a script mvf.sh to create the _mvf.so file:
swig -python mvf.i
gcc -fpic -c mvf.c mvf_wrap.c -I/usr/local/include/python2.3
gcc -shared mvf_wrap.o mvf.o -lm -O3 -o _mvf.so

and finally the Python test:

Python 2.3.3 (#1, Feb 4 2004, 13:34:29)
[GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-2mdk)] on linux2
import mvf
a = mvf.doubleArray(2)
a[0] = 1.0; a[1] = 2.0;
mvf.SumSquares(2, a) DEBUGGING: 5.000000 # C code ok!
0.0 # !!!??? ... expecting a 5.0

What could have gone wrong?

TIA,

Ernie
Jul 18 '05 #1
1 3701
Ernie wrote:
Here is the swig file mvf.i:
%module mvf
%include "carrays.i"
%array_class(double, doubleArray);
%typemap(out) double, float "\$result = PyFloat_FromDouble(\$1);"
%include mvf.h
<snip>
What could have gone wrong?

You need to add a verbatim block near the top of your SWIG interface
file, e.g.

%module mvf

%{
#include "mvf.h"
%}

%include "carrays.i"
%array_class(double, doubleArray);

%include mvf.h

Otherwise, there's no declaration of SumSquares() in the SWIG-generated
mvf_wrap.c file, and the compiler assumes that SumSquares() returns an
For more information on why this is needed, see the "Input format"
section of the "SWIG Basics" chapter of the SWIG documentation:

http://www.swig.org/Doc1.3/SWIG.html#n3

I've also removed the "out" typemap for double and float, since that's
built in and doesn't need to be explicitly specified.

Hope this helps,

Lyle
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.