C++ 扩展python(四)传递numpy(使用SWIG)

这篇博客介绍了如何使用SWIG扩展Python,以实现对numpy数组进行cos运算的功能。作者首先提到numpy.i文件在某些库中可能缺失,需要单独下载。接着,展示了创建C++模块cos_doubles的过程,包括编写C++头文件和源文件,以及接口文件。通过SWIG和distutils打包,确保numpy.i被正确引用。由于初始的setup.py无法处理C++源码,作者调整了编译方法,并成功生成了Python模块。最后,提供了测试代码和参考资料链接。
摘要由CSDN通过智能技术生成

前期准备:

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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值