How to define in Cython an external C++ function which has input parameters as enums? MKL

这一生的挚爱 提交于 2019-12-10 20:28:29

问题


So trying to wrap this in Cython from MKL, and digging in the mkl_cblas.h I see these are enums:

typedef enum {CblasRowMajor=101, CblasColMajor=102} CBLAS_ORDER;
typedef enum {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113} CBLAS_TRANSPOSE;

And here is the function declaration:

void cblas_dgemm(const  CBLAS_LAYOUT Layout, const  CBLAS_TRANSPOSE TransA,
                 const  CBLAS_TRANSPOSE TransB, const MKL_INT M, const MKL_INT N,
                 const MKL_INT K, const double alpha, const double *A,
                 const MKL_INT lda, const double *B, const MKL_INT ldb,
                 const double beta, double *C, const MKL_INT ldc);

The Cython documentation is lacking in this area as it seems to suggest converting everything to int but then the MKL function complains I haven't passed it the correct type (the enums CBLAS_LAYOUT and CBLAS_TRANSPOSE are not type int).

What is the proper way to define these from Cython? I.e.:

cimport cython

cdef extern from "mkl.h" nogil:
      ctypedef enum CBLAS_LAYOUT:
          CblasRowMajor
          CblasColMajor
      ctypedef enum CBLAS_TRANSPOSE:
          CblasNoTrans
          CblasTrans
          CblasConjTrans
      void dgemm "cblas_dgemm"(CBLAS_LAYOUT Layout,
                               CBLAS_TRANSPOSE TransA,
                               CBLAS_TRANSPOSE TransB,
                               int M,
                               int N,
                               int K,
                               double alpha,
                               double *A,
                               int lda,
                               double *B,
                               int ldb,
                               double beta,
                               double *C,
                               int ldc                              
                              )

The above compiles fine with no errors. But I didn't get results in C (until I changed it to CblasColMajor calling dgemm after I posted this). So wondering if anyone confirm if the above is correct way to do it.

I profiled the above vs. the SciPy built in version Using the Scipy cython_blas interface from Cython not working on vectors Mx1 1xN and they're about the same speed (my SciPy is linked to MKL), so I imagine the above is correct but if there's a better / faster way to do it then please post suggestions. Nonetheless I'll leave this posted for others since it doesn't look documented well in Cython.

来源:https://stackoverflow.com/questions/44990126/how-to-define-in-cython-an-external-c-function-which-has-input-parameters-as-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!