无法使用 SWIG 在 Python 中实例化 C++ class(获取属性错误)
Cannot instantiate a C++ class in Python using SWIG (Gets Attribute error)
我想将 C++ classes 导出到 Python,为此我使用 SWIG 创建了一个 C++ 扩展模块。从文档中,我可以看到 classes 可以使用 SWIG 导出。我能够成功地为 python 创建 class 模块 (_minimal.pyd)。我可以在 Python 中导入模块。但是,我无法创建 class 的对象,并且出现属性错误。请找到我尝试过的代码示例。谁能帮帮我?
//minimal.h
class minimal
{
private:
static int num_instances;
public:
minimal()
{
++num_instances;
}
~minimal()
{
--num_instances;
}
void print_num_instances();
};
//minimal.cpp
#include <iostream>
#include "minimal.h"
int minimal::num_instances = 0;
void minimal::print_num_instances()
{
using namespace std;
cout << this->num_instances << endl;
}
//minimal.i(interface file)
%module minimal
%{
#include "minimal.h"
%}
%include "minimal.h"
//python code used to run the module
import _minimal as m
m1=m.minimal()
SWIG 生成 minimal_wrap.cxx
和 minimal.py
。当您将 .cxx 文件构建到 _minimal.pyd
中时,您将 import minimal
而不是 import _minimal
.
>>> import minimal
>>> x=minimal.minimal()
>>> x.print_num_instances()
1
>>> y=minimal.minimal()
>>> x.print_num_instances()
2
有关参考,请参阅 SWIG Python 文档中的 36.2.1 Running SWIG。引用:
...[Running swig -c++ -python] This creates two different files; a C/C++ source file example_wrap.c or example_wrap.cxx and a Python source file example.py. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module. The Python source file contains high-level support code. This is the file that you will import to use the module.
我想将 C++ classes 导出到 Python,为此我使用 SWIG 创建了一个 C++ 扩展模块。从文档中,我可以看到 classes 可以使用 SWIG 导出。我能够成功地为 python 创建 class 模块 (_minimal.pyd)。我可以在 Python 中导入模块。但是,我无法创建 class 的对象,并且出现属性错误。请找到我尝试过的代码示例。谁能帮帮我?
//minimal.h
class minimal
{
private:
static int num_instances;
public:
minimal()
{
++num_instances;
}
~minimal()
{
--num_instances;
}
void print_num_instances();
};
//minimal.cpp
#include <iostream>
#include "minimal.h"
int minimal::num_instances = 0;
void minimal::print_num_instances()
{
using namespace std;
cout << this->num_instances << endl;
}
//minimal.i(interface file)
%module minimal
%{
#include "minimal.h"
%}
%include "minimal.h"
//python code used to run the module
import _minimal as m
m1=m.minimal()
SWIG 生成 minimal_wrap.cxx
和 minimal.py
。当您将 .cxx 文件构建到 _minimal.pyd
中时,您将 import minimal
而不是 import _minimal
.
>>> import minimal
>>> x=minimal.minimal()
>>> x.print_num_instances()
1
>>> y=minimal.minimal()
>>> x.print_num_instances()
2
有关参考,请参阅 SWIG Python 文档中的 36.2.1 Running SWIG。引用:
...[Running swig -c++ -python] This creates two different files; a C/C++ source file example_wrap.c or example_wrap.cxx and a Python source file example.py. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module. The Python source file contains high-level support code. This is the file that you will import to use the module.