Meddle
Meddle

Reputation: 21

C functions wrapped with f2py return only zeros

I am trying to wrap a simple C function using f2py. It compiles all right, but the function returns only zero. I am a novice in C, so I am pretty sure making a silly mistake there.

For example, the c file:

#include <stdio.h>
#include <stdlib.h>
void Test(double x, double y)
{
  x = y*2;
}

The pyf file:

python module test
interface
   subroutine Test(x, y)        
     intent (c) Test  ! is a C function
     intent (c)         ! all arguments are considered as C based
     double precision intent(in)     :: x
     double precision intent(out)    :: y
   end subroutine Test
end interface
end python module test

Upvotes: 2

Views: 409

Answers (3)

rth
rth

Reputation: 11201

To solve this problem, you need

  1. To use pointers for the return variable in the .c function as mentioned by @mgilson,

    void Test(double *x, double y)
    {
       *x = y * 2;
    }
    
  2. Specify in the .pyf interface that pointers are used, which is incidentally identical arrays of size 1,

    double precision intent(out)   :: x(1)
    double precision intent(in)    :: y
    

The test.Test function will then return not a scalar, but a numpy ndarray of length 1, containing that scalar. Still, I'm not sure if there is another way of dealing with it.

Upvotes: 4

Matt Ko
Matt Ko

Reputation: 979

EDIT: my first answer was wrong, the values should indeed be passed to C as pointers, as pointed out by others.

void Test(double* x, double* y)
{
    *y = *x * 2;
}

Upvotes: 0

mgilson
mgilson

Reputation: 309929

I'm no expert in C, but I think your variables need to be pointers for anything to change:

void Test(double *x, double *y)
{
  *x = *y * 2;
}

Upvotes: 2

Related Questions