簡體   English   中英

如何在 python (SWIG) 中調用 C++ 成員 function?

[英]How to call a C++ member function in python (SWIG)?

I want to expose my C++ library class to python and be able do call any function contained in that class in python. 我的示例庫如下所示:

#include "example_lib.h"

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

使用 header:

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

但是當我嘗試調用成員 function example_lib.lib.test(1)時,我只得到類型 object 'lib' has no attribute 'test' 如何讓 swig 也暴露成員 function? 這似乎是一個非常基本的問題,但如果有人能澄清它通常是如何完成的,我將非常感激。

默認可訪問性在 C++ 中是private的,然后您需要將其移動到public:部分:

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

另請注意, test是一個實例方法,您需要實例化 class。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM