You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SWIG向Python传递std::vector<std::vector<double>>指针的技术咨询

使用SWIG实现Python调用带输出参数的C++函数

我正在尝试用SWIG让Python调用一个C++的coverage函数,这个函数有三个参数,其中最后一个参数是作为输出返回值来使用的。目前我写的代码片段如下:

analysis.i 代码片段

%module coverage
%{
//#include "../SeqMCMC/src/funeval_base.hpp"
#include "coverage.hpp"
%}
%include "std_vector.i"
void coverage(std::vector<double> *Pypar, std::vector<std::vector<double>> *Pyxpass, std::vector<std::vector<double>> *Pyypass);

coverage.hpp 代码片段

#ifndef _COVERAGE_
#define _COVERAGE_
#include<vector>
void coverage(std::vector<double> *Pypar, std::vector<std::vector<double>> *Pyxpass, std::vector<std::vector<double>> *Pyypass);
// 此处原代码被截断,后续应该是函数的具体实现声明
#endif

实用提示

  • 由于用到了C的std::vector,必须包含std_vector.i,这样SWIG才能自动完成C向量和Python列表之间的类型转换,避免类型不兼容问题。
  • 对于作为输出参数的指针(也就是这里的Pyypass),SWIG默认支持这种指针参数的处理。在Python调用时,你可以传入一个空列表,函数执行完成后,这个列表会被自动填充函数生成的结果。如果想更优雅地处理输出参数,也可以使用SWIG的%pointer_class或%reference指令来优化,但当前的写法已经能满足基本需求。
  • 编译生成Python扩展模块的大致步骤(以Linux环境为例):
    # 生成SWIG包装代码
    swig -c++ -python analysis.i
    # 编译包装代码和C++源文件(替换python3.x为你的Python版本对应路径)
    g++ -fPIC -c analysis_wrap.cxx coverage.cpp -I/usr/include/python3.x
    # 链接生成共享库
    g++ -shared analysis_wrap.o coverage.o -o _coverage.so
    
  • Python中的调用示例:
    import coverage
    
    # 准备输入参数
    par = [1.5, 2.3, 3.7]
    xpass = [[0.1, 0.2], [0.3, 0.4]]
    # 初始化输出参数容器
    ypass = []
    
    # 调用C++函数
    coverage.coverage(par, xpass, ypass)
    
    # 此时ypass已经被填充了函数返回的结果
    print(ypass)
    

内容的提问来源于stack exchange,提问作者user1512321

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:08:05