swig: conversion of C double to Python float

E

Ernie

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*x;
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
Type "help", "copyright", "credits" or "license" for more information.
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
 
L

Lyle Johnson

Ernie said:
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

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
int instead of a double. (You would see a warning about this if you
added the -Wall flag to your compiler flags when compiling mvf_wrap.c).
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top