【问题标题】:SWIG : AttributeError: 'module' object has no attribute 'fact'SWIG:AttributeError:“模块”对象没有属性“事实”
【发布时间】:2015-05-07 07:02:16
【问题描述】:

我正在研究如何使用 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

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

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(example) 时的输出:

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

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

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

【问题讨论】:

  • 也许:“gcc -shared -o _example.so example_wrap.o”可以解决问题,通常链接到库的内容放在.so之后。
  • @Tony 还是不行。
  • 好的,如果链接不正确,则可能是“gcc -shared -Wl,-soname, _example.so -o _example.so example_wrap.o”。抱歉,如果它没有帮助,我不使用 SWIG,但我在使用 boost.python 时遇到了类似的问题,它们与编译有关。

标签: python c swig


【解决方案1】:

请尝试如下替换:

%#include "example.h"

通过

%include "example.h"

【讨论】:

    【解决方案2】:

    Reference

    尝试将 Makefile 更改为

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

    我假设您只有一种导出方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2013-02-13
      • 2010-11-18
      • 2019-01-03
      • 2017-05-19
      • 2013-02-01
      相关资源
      最近更新 更多