【问题标题】:How to call a C++ member function in python (SWIG)?如何在 python (SWIG) 中调用 C++ 成员函数?
【发布时间】:2021-06-14 17:32:35
【问题描述】:

我想将我的 C++ 库类公开给 python,并能够在 python 中调用该类中包含的任何函数。 我的示例库如下所示:

#include "example_lib.h"

lib::lib(){};
int lib::test(int i){
return i;
}

带有标题:

class lib{
  lib();
  int test(int i);
};

我的接口文件:

/* example_lib.i */
%module example_lib
%{
   /* Put header files here or function declarations like below */
   #include "example_lib.h"
%}
%include "example_lib.h"

我运行以下命令:

swig3.0 -c++ -python example_lib.i 
g++ -c -fPIC example_lib.cc example_lib_wrap.cxx -I/usr/include/python3.8
g++ -shared -fPIC example_lib.o example_lib_wrap.o -o _example_lib.so

但是当我尝试调用成员函数时 example_lib.lib.test(1), 我只得到类型对象'lib'没有属性'test'。如何让 swig 也暴露成员函数? 这似乎是一个非常基本的问题,但如果有人能澄清它通常是如何完成的,我将非常感激。

【问题讨论】:

    标签: python c++ swig


    【解决方案1】:

    C++ 中的默认可访问性是 private,然后您需要将其移动到 public: 部分:

    class lib{
      public:
        lib();
        int test(int i);
    };
    

    还要注意test是实例方法,需要实例化类。

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 2011-04-02
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 2012-01-10
      相关资源
      最近更新 更多