我有一个 C++ 库,其中包含一个使用结构体引用构造的类:
myclass.hpp:
className::className (params& pars): memberInitList
{
//some code that modifies state of params
}
我的 swig 界面文件看起来像这样
我的界面.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 应该能够很好地处理引用传递,所以我不确定这里的问题是什么。任何帮助将不胜感激!
编辑: 我已经在互联网上寻找可能的解决方案,包括 SWIG 文档,但没有解决方案有效。 我试过了
%include <typemaps.i>
%apply params &INPUT { params& params}
Binary::Binary(params& params)
但这不起作用。
编辑:MWE 这是一个非常小的工作示例,它是我的代码的基本工作,并准确地重现了我的错误:
示例.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
示例.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;
};
示例.i
%module example
%{
#include "example.hpp"
%}
%include "example.hpp"
啊,由于这个类似的问题,我解决了这个问题。问题是,在 python 解释器中,我没有将结构称为
example.tmpStruct()
而是
example.tmpStruct
所以结构没有被初始化。正确初始化结构并将其传递给类构造函数可以按预期工作。