C++ 擴展python(四)傳遞numpy(使用SWIG)

前期準備:

numpy.i文件,有些conda下載的numpy庫裏面自帶,而有些沒有(比如我的,,),可以去下載numpy.i源碼

我們實現一個cos_doubles模塊的cos_double函數來對numpy數組求cos, 並返回他的cos值到一個新的numpy數組中:

測試樣例test.py如下:

import numpy as np
import cos_doubles

x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x)

cos_doubles.cos_doubles_func(x, y)
print(x)
print(y)

首先我們先實現cos_doubles 的C版本: cos_doubles.h

void cos_doubles(double * in_array, double * out_array, int size);

cos_doubles.c

#include <math.h>
#include "cos_doubles.h"

/*  Compute the cosine of each element in in_array, storing the result in
 *  out_array. */
void cos_doubles(double * in_array, double * out_array, int size){
    int i;
    for(i=0;i<size;i++){
        out_array[i] = cos(in_array[i]);
    }
}

然後我們藉助swig的接口文件 cos_doubles.i 實現擴展:

/*  Example of wrapping a C function that takes a C double array as input using
 *  numpy typemaps for SWIG. */

%module cos_doubles
%{
    /* the resulting C file should be built as a python extension */
    #define SWIG_FILE_WITH_INIT
    /*  Includes the header in the wrapper code */
    #include "cos_doubles.h"
%}

/*  include the numpy typemaps */
%include "numpy.i"
/*  need this for correct module initialization */
%init %{
    import_array();
%}

/*  typemaps for the two arrays, the second will be modified in-place */
%apply (double* IN_ARRAY1, int DIM1) {(double * in_array, int size_in)}
%apply (double* INPLACE_ARRAY1, int DIM1) {(double * out_array, int size_out)}

/*  Wrapper for cos_doubles that massages the types */
%inline %{
    /*  takes as input two numpy arrays */
    void cos_doubles_func(double * in_array, int size_in, double * out_array, int size_out) {
        /*  calls the original funcion, providing only the size of the first */
        cos_doubles(in_array, out_array, size_in);
    }
%}

...我一開始忘了寫import_array後面的;

  • 爲了使用Numpy類型映射,需要numpy.i文件。
  • 觀察import_array()的調用
  • 因爲類型映射僅僅支持參數ARRAY, SIZE我們需要包裹cos_doublescos_doubles_func,該函數接受兩個數組包含各自大小作爲輸入。
  • 相對於簡單SWIG的例子,我們不需要包含cos_doubles.h頭文件,因爲我們通過cos_doubles_func暴露這個功能,我們沒有其它東西想暴露給Python。

然後通過distutils來包裝他,如果在你的numpy庫中包含了numpy.i,則需要include_dirs來指定位置。否則你可以把numpy.i放在當前目錄下。

from distutils.core import setup, Extension
import numpy

setup(ext_modules=[Extension("_cos_doubles",
      sources=["cos_doubles.c", "cos_doubles.i"],
      include_dirs=[numpy.get_include()])])

之前每次編譯都出錯,說我沒有實現cos_doubels()函數。

後來才發現是因爲我把函數寫到了cpp文件裏面,而上述的setup的方式,只能夠實現c的轉換,而對於c++的源碼,可以採用下述方式:

swig -c++ -python cos_doubles.i

可以看到生成了兩個文件cos_doubles.py與cos_doubles_wrap.cxx,然後setup.py修改爲:

from distutils.core import setup, Extension
import numpy

setup(ext_modules=[Extension("_cos_doubles",
      sources=["cos_doubles.cpp", "cos_doubles_wrap.cxx"],
      include_dirs=[numpy.get_include()])])

然後運行命令

python setup.py build_ext --inplace

運行測試代碼test.py就可以發現現在cos_module可以正常使用了。

 

本文借鑑自

https://segmentfault.com/a/1190000000479951

https://blog.csdn.net/ustczhang/article/details/78147215

https://stackoverflow.com/questions/58460470/how-to-use-numpy-i-in-swig

https://stackoverflow.com/questions/51598137/swig-function-that-modifies-its-argument-from-c-to-python/51614104#51614104

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章