【问题标题】:SWIG tutorial problemsSWIG 教程问题
【发布时间】:2016-10-03 07:15:51
【问题描述】:

我正在尝试遵循 swig 教程,但我卡住了,现在我正在使用:

  • Win32 上的 Python 3.5.1(v3.5.1:37a07cee5969,2015 年 12 月 6 日,01:54:25)[MSC v.1900 64 位 (AMD64)]
  • Vs2015 x64,Microsoft (R) C/C++ 优化编译器版本 19.00.23918 for x64
  • SWIG 版本 3.0.10

内容是:

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);
 }

 char *get_time()
 {
     time_t ltime;
     time(&ltime);
     return ctime(&ltime);
 }

example.i

 %module example
 %{
 /* Put header files here or function declarations like below */
 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();
 %}

 extern double My_variable;
 extern int fact(int n);
 extern int my_mod(int x, int y);
 extern char *get_time();

然后我做:

  • swig -python example.i
  • cl /D_USRDLL /D_WINDLL example.c example_wrap.c -Ic:\Python351\include /link /DLL /out:example.pyd /libpath:c:\python351\libs python35.lib

但是当我尝试python -c "import example" 我得到:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: dynamic module does not define module export function (PyInit_example)

问题,这是怎么回事,我该如何解决?

【问题讨论】:

    标签: python c++ windows visual-studio-2015 swig


    【解决方案1】:

    SWIG 的动态链接模块的名称应以下划线开头,在本例中为 _example.pyd。 SWIG 生成的 Python 文件正在寻找名为 _example 的模块,请参见该文件的开头:

    from sys import version_info
    if version_info >= (2, 6, 0):
        def swig_import_helper():
            from os.path import dirname
            import imp
            fp = None
            try:                                           # ↓ SEE HERE
                fp, pathname, description = imp.find_module('_example', [dirname(__file__)])
            except ImportError:
                import _example # ← AND HERE
                return _example # ← AND HERE
            if fp is not None:
                try:                      # ↓ AND HERE
                    _mod = imp.load_module('_example', fp, pathname, description)
                finally:
                    fp.close()
                return _mod
        _example = swig_import_helper() # ← AND HERE
        del swig_import_helper
    else:    # ↓ AND HERE
        import _example
    

    实际上是被 SWIG 包装的 C++ 模块的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-10
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 2021-02-15
      • 2019-09-06
      相关资源
      最近更新 更多