使用SWIG在成员中用互斥体包装C++类的问题

2024-05-20 05:28:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个C++类,包含一个(POCO)互斥:

class ClassWithMutex
{
    public:
                                ClassWithMutex();
        virtual                 ~ClassWithMutex();

        Poco::Mutex             mMyMutex;

    private:
        ClassWithMutex(const ClassWithMutex& );
        ClassWithMutex& operator=(const ClassWithMutex& other);

};

另一个类,使用它:

class ClassHavingAClassWithMutex
{
    public:
        ClassHavingAClassWithMutex();
        ~ClassHavingAClassWithMutex();
        ClassWithMutex      A;

    private:
        ClassHavingAClassWithMutex(const ClassHavingAClassWithMutex&);
        ClassHavingAClassWithMutex& ClassHavingAClassWithMutex::operator=(const ClassHavingAClassWithMutex& other);

};

尝试为ClassHavingClassWithMutex创建包装时,出现错误:

Error   C2248   'ClassWithMutex::operator =': cannot access private member declared in class 'ClassWithMutex'   mvr C:\builds\vs2015\mvr\python_package\src\mvr\mvrPYTHON_wrap.cxx  6493    

Swig生成的代码如下所示:

SWIGINTERN PyObject *_wrap_ClassWithMutex_mMyMutex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
  PyObject *resultobj = 0;
  ClassWithMutex *arg1 = (ClassWithMutex *) 0 ;
  void *argp1 = 0 ;
  int res1 = 0 ;
  PyObject *swig_obj[1] ;
  Poco::Mutex result;

  if (!args) SWIG_fail;
  swig_obj[0] = args;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ClassWithMutex, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ClassWithMutex_mMyMutex_get" "', argument " "1"" of type '" "ClassWithMutex *""'"); 
  }
  arg1 = reinterpret_cast< ClassWithMutex * >(argp1);
  {
    SWIG_PYTHON_THREAD_BEGIN_ALLOW;
    result =  ((arg1)->mMyMutex);
    SWIG_PYTHON_THREAD_END_ALLOW;
  }
  resultobj = SWIG_NewPointerObj((new Poco::Mutex(static_cast< const Poco::Mutex& >(result))), SWIGTYPE_p_Poco__Mutex, SWIG_POINTER_OWN |  0 );
  return resultobj;
fail:
  return NULL;
}

以及由此行发出的错误:

if (arg1) (arg1)->A = *arg2;
and
resultobj = SWIG_NewPointerObj((new Poco::Mutex(static_cast< const Poco::Mutex& >(result))), SWIGTYPE_p_Poco__Mutex, SWIG_POINTER_OWN |  0 );

Swig接口文件:

%immutable
%include "aiClassWithMutex.h"
%include "ClassHavingAClassWithMutex.h"
%mutable

关于如何用Swig正确包装上面的类有什么建议吗?为了防止任何复制,我在上面的类中把拷贝和赋值都做了私有的,但是好像swig坚持要这样做?你知道吗


Tags: resultprivateclassswigpyobjectpocomutexres1
1条回答
网友
1楼 · 发布于 2024-05-20 05:28:15

这不是由复制构造函数引起的,而是属性设置器(b/cA是公共的)。如评论中所讨论的,一个选项是通过添加以下内容来隐藏它:

%ignore ClassWithMutex::mMyMutex;

在.i文件中的%include "aiClassWithMutex.h"之前。你知道吗

同样如前所述,SWIG在使mMyMutex不可变时使用复制。但是,除了写一个排版图和错误地使用optimal设置(首先要防止临时文件的构建)之外,没有别的方法可以解决这个问题。这样,函数.i文件看起来像:

%module mut

%{  
#include "aiClassWithMutex.h"
#include "ClassHavingAClassWithMutex.h"
%}      

%feature("immutable", 1) ClassWithMutex::mMyMutex;
%typemap(out, optimal="1") Poco::Mutex %{
  $result = SWIG_NewPointerObj(($1_ltype*)&$1, $&1_descriptor, 0);
%}      
%include "aiClassWithMutex.h"
%include "ClassHavingAClassWithMutex.h"

相关问题 更多 >