By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,372 Members | 1,207 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,372 IT Pros & Developers. It's quick & easy.

swig: conversion of C double to Python float

P: n/a

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 to create the 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

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?


Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply

P: n/a
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
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:

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,

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.