SWIG包装器未声明(此功能首次使用)

问题描述 投票:0回答:1

我正在尝试为C ++代码创建包装器,以便在python项目中使用它。该代码取自here(主要是mtree.h)。

我正在使用swig通过以下方式生成接口:swig -python -module mtree mtree.h

然后当我尝试gcc -c -fpic mtree_wrap.c时出现以下错误:

user@ubuntu:~/git/M-Tree/cpp2python(master)$ gcc -c -fpic mtree_wrap.c
mtree_wrap.c: In function ‘Swig_var_mt_set’:
mtree_wrap.c:3029:7: error: ‘mt’ undeclared (first use in this function)
       mt = *((namespace *)(argp));
       ^~
mtree_wrap.c:3029:7: note: each undeclared identifier is reported only once for each function it appears in
mtree_wrap.c:3029:15: error: ‘namespace’ undeclared (first use in this function); did you mean ‘isspace’?
       mt = *((namespace *)(argp));
               ^~~~~~~~~
               isspace
mtree_wrap.c:3029:26: error: expected expression before ‘)’ token
       mt = *((namespace *)(argp));
                          ^
mtree_wrap.c: In function ‘Swig_var_mt_get’:
mtree_wrap.c:3041:47: error: ‘mt’ undeclared (first use in this function)
   pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&mt), SWIGTYPE_p_namespace,  0 );
                                               ^
mtree_wrap.c:1163:89: note: in definition of macro ‘SWIG_NewPointerObj’
 ointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(NULL, ptr, type, flags)
                                                                        ^~~
mtree_wrap.c:3041:30: note: in expansion of macro ‘SWIG_as_voidptr’
   pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&mt), SWIGTYPE_p_namespace,  0 );
                              ^~~~~~~~~~~~~~~

这是发生错误的mtree.c

SWIGINTERN int Swig_var_mt_set(PyObject *_val) {
  {
    void *argp = 0;
    int res = SWIG_ConvertPtr(_val, &argp, SWIGTYPE_p_namespace,  0 );
    if (!SWIG_IsOK(res)) {
      SWIG_exception_fail(SWIG_ArgError(res), "in variable '""mt""' of type '""namespace""'");
    }
    if (!argp) {
      SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""mt""' of type '""namespace""'");
    } else {
      mt = *((namespace *)(argp));
    }
  }
  return 0;
fail:
  return 1;
}


SWIGINTERN PyObject *Swig_var_mt_get(void) {
  PyObject *pyobj = 0;

  pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&mt), SWIGTYPE_p_namespace,  0 );
  return pyobj;
}

任何解决方案?

python c++ wrapper swig
1个回答
0
投票

首先,使用C ++模式的Swig,并使用-c++开关。但这对您没有任何好处。 Swig无法为模板类创建包装器。您需要创建适当的swg文件并声明应在python中使用的模板规范。像这样:

%module strmtree;

//generate good wrapper for std::string -> python string
%include "stdstring.i"

%{
//include actualy header in wrapper
#include "mtree.h"
%}

//generate wrapper for class in this file,
//but since the class is template, it won't generate anything on it's own.
%include "mtree.h"

//declare template specialization for string and call it StrMTree.
//ideally you'll get StrMTree class in python
%template(StrMTree) mt::mtree<std::string>;

不知道mtree模板参数通常应该使用哪种类型。如果您想要python对象的mtree,则要复杂得多...您可能想要某种C ++接口,使用该接口对mtree进行特殊化,然后在python中实现if接口。

© www.soinside.com 2019 - 2024. All rights reserved.