0

I have a function in C like this:

source file

// foo.cpp
int foo(int input1, double *output1, int size1, int* output2, int size2)
{
// does stuff and allocate space for output1 and output2
    return 0;
}

header file

// foo.h
int foo(int input1, double *output1, int size1, int* output2, int size2);

In Cython I need to convert output1 and output2 to a numpy array, so in my foo.pyx I do the following steps:

cdef extern from "foo.h":
    cdef int foo(int input1, double* output1, int size1, double* output2, int size2) 

cdef double* ptnOutput1
cdef int* ptnOutput2

foo(1, ptnOutput1, 10, ptnOutput2, 10)

but now I'm not able to get the output in form of two np.array. How should I align the pointers ptnOutput1 and ptnOutput2 to two numpy arrays? I've tried np.frombuffer as well as np.PyArray_SimpleNewFromData but with no luck. I always get segmentation fault. Any idea how to do it correctly?

2
  • 2
    Ignoring the Cython aspect of it for the moment, how would you call this in C? I'd have thought ptnOutput1 and ptnOutput2 need to already be allocated when you call foo (which then fills in their contents)? Commented Nov 4, 2016 at 16:32
  • cython.readthedocs.io/en/latest/src/userguide/memoryviews.html is a good description of how to work with arrays, cython native memoryviews and C arrays. Commented Nov 4, 2016 at 17:06

1 Answer 1

1

The numpy documentation mentions that

In order to make use of the C-API from another extension module, the import_array function must be called

It seems you got the segmentation fault error because you didn't include import_array in your code.

The internal machinery of import_array is more complex than what you may expect because it's actually a very lengthy macro, not a plain function. Refer to this for more information

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.