简体   繁体   中英

Wrapping a C++ struct in Cython

I am trying to Cython-wrap a dll written in C++ with the following header file:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

struct cmplx64
{
    float re;
    float im;
};

EXTERN_DLL_EXPORT int foo(cmplx64 *arr, int arr_sz);

The PXD file:

cdef extern from "mylib.h":

    cdef struct cmplx64:
        np.float64_t re
        np.float64_t im

    int foo(cmplx64 *arr, int arr_sz) except +

The PYX file:

cimport cmylib
import numpy as np
cimport numpy as np
import cython

def foo(np.ndarray[np.complex64_t, ndim=1] arr, int arr_sz):

    return cmylib.foo(&arr[0], arr_sz)

The problem does not appear with my setup file.

In lieu of the struct definition, I have tried building a cppclass per a suggestion I found, but I did not get as far with that as this current method.

The error message I am getting is:

Cannot assign type 'float complex *' to 'complexFloatStruct *'

My problem is caused by the fact that the author of the library I'm using defined a complex type with a struct rather than simply using the built in complex type in the C++ std library. If that were the case, I would have no issue.

However, it seems perfectly reasonable that I should be able to wrap a C++ class or struct with Cython. I have been over the documentation and have pretty much failed. Thanks for your help!

A simple cast might be sufficient,

def foo(np.ndarray[np.complex64_t, ndim=1] arr, int arr_sz):
    return cmylib.foo(<cmylib.cmplx64 *>&arr[0], arr_sz)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM