SWIG实现C++转Python:结构体引用初始化类失败求助
问题:SWIG处理C++结构体引用构造函数时的类型错误
问题背景
我有一个C++库,其中包含一个通过结构体引用进行构造的类:
myclass.hpp
className::className (params& pars): memberInitList { // 此处代码会修改params的状态 }
对应的SWIG接口文件如下:
myInterface.i
%module MyLibrary %{ #include "myclass.hpp" %} %include "include/myclass.hpp"
根据SWIG文档第33.3.9节的说明,SWIG应该可以正常处理按引用传递的参数,但运行生成的Python包时,出现以下错误:
TypeError: in method 'new_className', argument 1 of type 'params &'
我不确定问题出在哪里,需要帮助排查。
已尝试的无效方案
我查阅过网络资料和SWIG文档,尝试过以下方法但未解决问题:
%include <typemaps.i> %apply params &INPUT { params& params} Binary::Binary(params& params)
最小复现示例(MWE)
以下是能完全复现该错误的极简代码:
example.hpp
#ifndef included #define included #include <vector> #include <iostream> using high_prec_t=double; //boost::multiprecision::cpp_dec_float<25>; struct tmpStruct { high_prec_t x { 0. }; std::string y { "hello" }; int z { 0 }; std::vector<high_prec_t> w{}; double f{0.}; }; class tmpClass { protected: high_prec_t m_x; std::string m_y; int m_z; std::vector<high_prec_t> m_w; double m_f; public: tmpClass(tmpStruct& myStruct); high_prec_t myFun(); }; #endif
example.cpp
#include "example.hpp" #include <iostream> tmpClass::tmpClass(tmpStruct& myStruct): m_x { myStruct.x }, m_y { myStruct.y }, m_z { myStruct.z }, m_w { myStruct.w }{ m_f = myStruct.f; }; high_prec_t tmpClass::myFun() { return m_f*m_x; };
example.i
%module example %{ #include "example.hpp" %} %include "example.hpp"
内容的提问来源于stack exchange,提问作者shanedrum
相关产品推荐
相关产品推荐

