python - 痛饮 : AttributeError: 'module' object has no attribute 'fact'

标签 python c swig

我正在研究如何使用 swig 为我的 python 代码进行 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);
 }

example.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"

生成文件

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

测试.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"

关于python - 痛饮 : AttributeError: 'module' object has no attribute 'fact' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30094061/

相关文章:

python openpyxl 获取工作表名称

c - C 形式定义中的命名空间

c++ - 在 C++ 代码中释放 Python GIL

python - 从标签和辨别值中学习阈值?

python - cherrypy 演示中缺少 tutorial.conf 文件

python - 是否有等同于wx.FutureCall(在窗口初始化和绘制后调用函数)的PyQT?

C 编程函数无参数返回 printf 语句

c - 如何拥有一个返回整数指针的函数数组

php - 加载使用 SWIG 制作的 php 扩展时 undefined symbol

python - 无法为 Python 3.6 重新编译 webbot