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

swig: conversion of C double to Python float

P: n/a
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
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
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
<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
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
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.