SWIG:属性错误:"模块"对象没有属性"事实"



我正在研究如何使用 swig 对我的Python代码进行C扩展。我以网站从网站上获得的代码进行了c扩展。这是我的代码:

example.c

 #include <time.h>
 double My_variable = 3.0;
 int fact(int n) {
     if (n <= 1) return 1;
     else return n*fact(n-1);
 }
 int my_mod(int x, int y) {
     return (x%y);
 }

示例.h

#ifndef EXAMPLE_H_
#define EXAMPLE_H_
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
#endif

示例.i

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

makefile

all:
    rm -f *.so *.o *_wrap.* *.pyc
    swig -python example.i
    gcc -c -fPIC example_wrap.c -I/usr/include/python2.7
    gcc -shared  example_wrap.o -o _example.so
clean:
    rm -f *.so *.o *_wrap.* *.pyc

test.py

import example
print str(example.fact(2))

test.py用于检查扩展是否有效。但是当我运行test.py时,它会输出:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print str(example.fact(2))
AttributeError: 'module' object has no attribute 'fact'

这是我使用dir时的输出(示例):

['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_example', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic']

出现此输出的原因是什么?

如果我想成功运行该程序,我该怎么办?

请尝试替换如下:

%#include "example.h"

%include "example.h"

参考

尝试将makefile更改为

%module example
%{
   #include "example.h" 
%}
int fact(int n);

我以为您只有一种方法来导出

最新更新