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

SWIG将Python数组传递给C++类内函数时出现未定义符号错误如何解决

问题根因

  • 第一个问题:test.cpp中实现的print_array是全局函数,没有加myClass::类作用域标识,编译器不会生成类成员函数对应的符号,导致加载动态库时找不到对应函数。
  • 第二个问题:test.i接口文件中print_array的参数带了const修饰,和test.hpp头文件中的函数声明不一致,也会导致符号匹配失败。

修正后的代码

1. 修正 test.cpp

#include "test.hpp"

void myClass::print_array(std::vector < double >  myarray)
{
  for (int i =0; i < myarray.size(); ++i) {
    // 原代码此处打印的是数组长度,要打印元素请替换为myarray[i]
    std::cout << myarray[i] << " ";
  }
  std::cout << std::endl;
}

2. 修正 test.i

%module test
%{
#include "test.hpp"
%}

%include "std_vector.i"

%template(Array) std::vector < double >;

class myClass {
public:
    // 移除const修饰,和头文件声明保持一致
    void print_array(std::vector < double > myarray);
}; 

修正后的编译命令

注意将Python的链接参数放到最后一步链接阶段,同时如果没有src目录,去掉-Isrc参数:

swig -python -c++ test.i
g++ -fPIC -c $(pkg-config --cflags python3) test.cpp test_wrap.cxx
g++ -shared -o _test.so test.o test_wrap.o $(pkg-config --libs python3)

测试代码

import test

# 实例化类
mc = test.myClass()
# 构造数组
arr = test.Array([1.2, 3.4, 5.6, 7.8])
# 调用类成员函数
mc.print_array(arr)

运行后会输出1.2 3.4 5.6 7.8 ,功能正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:15:03