[petsc-users] petsc4py: PetSc is no longer initialised when calling C Function from Cython

Jeff Wiens jeffrey.k.wiens at gmail.com
Thu Oct 20 15:05:08 CDT 2011


I am in the process of learning PetSc 3.1 and petsc4py 1.2. Since
there is so little documentation for petsc4py, I am resorting to the
PetSc mailing list. If anyone knows any resources for petsc4py, it
would be really helpful.

I am attempting to make a simple test problem where I
1)  Initialise PetSc from Python and then
2)  Call a "C" function, using Cython as a Wrapper, to construct and
perform a dot product for two Petsc Vectors.

I know there are better and simpler ways to deal with this problem.
However, this is a simple test problem which allows python PetSc
objects to interact with a Petsc C library.

The problem seems to be that PetSc is no longer initialised when you
call a C function. If I initialise PETSc from C, the program works.
However, if I don't call init() from C, the program won't use the
python PetSc. Eventually, I would like
to Initialise PETSc and construct my PETSc vectors in python and then
have my C code perform operations on them. Again, this yet another
test problem.

The code is as follows:

------- Python Code -----------

import sys, petsc4py
petsc4py.init(sys.argv)
from petsc4py import PETSc

import dot
val = dot.mydot()
PETSc.Sys.Print( "PETSc Dot Product: %i"%val )

------- Cython Code -----------

cdef extern from "c_files/dot.h":
   void init()
   double dot()

def mydot():
   #init();
   return dot();

------- C Code -----------

void init()
{	
    PetscInitialize(NULL,NULL,(char *)0,NULL);
}


double dot()
{	
    PetscScalar r;
    Vec v1,v2;

    VecCreate(PETSC_COMM_WORLD, &v1);
    VecCreate(PETSC_COMM_WORLD, &v2);

    VecSetSizes(v1, PETSC_DECIDE, 5000);
    VecSetSizes(v2, PETSC_DECIDE, 5000);
    VecSetFromOptions(v1);
    VecSetFromOptions(v2);

    VecSet(v1,1.0);
    VecSet(v2,2.0);

    VecAssemblyBegin(v1);
    VecAssemblyEnd(v1);
    VecAssemblyBegin(v2);
    VecAssemblyEnd(v2);

    VecDot(v1, v2, &r);
    return r;
}


More information about the petsc-users mailing list