无法运行Swig教程

时间:2019-04-06 18:55:50

标签: c++ python-3.x swig

我正在与

-Windows 10 64位

-Swig 3.0.12,我从http://www.swig.org/download.html下载

-win32上的Python 3.5.4 [MSC v.1900 64位(AMD64)]

-MinGW7.3.0 64位

这是我第一次使用swig用c ++代码扩展python应用程序。我试图编译swig官方网站a link的示例代码。 Python 3.5在libs文件夹中已经有libpython.a,需要使用mingw进行编译,因此我使用了它。我遵循了a link的教程!在Windows中编译Swig。

具体来说,我运行以下

swig –python –c example.i

gcc -c * .c

gcc -c example_wrap.cxx -Ic:\ python35 \ include

gcc -shared * .o -o _example.pyd -Lc:\ python35 \ libs -lpython35

到这里,一切都很好!

但是当我尝试将其导入Python35时,出现以下错误消息

Microsoft Windows [版本10.0.17763.379] (c)2018年微软公司。保留所有权利。

  

python

     

导入示例

     

example.fact(3)

     

回溯(最近通话最近):     文件“”,第1行,位于   TypeError:在“事实”方法中,类型为“ int”的参数1

错误在哪里?

/* File : example.c */

double  My_variable  = 3.0;

/* Compute factorial of n */
int fact(int n) {
  if (n <= 1)
    return 1;
  else
    return n*fact(n-1);
}

/* Compute n mod m */
int my_mod(int n, int m) {
  return(n % m);
}
/* File : example.i */
%module example
%{
/* Put headers and other declarations here */
extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
%}

extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.

from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
    def swig_import_helper():
        import importlib
        pkg = __name__.rpartition('.')[0]
        mname = '.'.join((pkg, '_example')).lstrip('.')
        try:
            return importlib.import_module(mname)
        except ImportError:
            return importlib.import_module('_example')
    _example = swig_import_helper()
    del swig_import_helper
elif _swig_python_version_info >= (2, 6, 0):
    def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_example', [dirname(__file__)])
        except ImportError:
            import _example
            return _example
        try:
            _mod = imp.load_module('_example', fp, pathname, description)
        finally:
            if fp is not None:
                fp.close()
        return _mod
    _example = swig_import_helper()
    del swig_import_helper
else:
    import _example
del _swig_python_version_info

try:
    _swig_property = property
except NameError:
    pass  # Python < 2.2 doesn't have 'property'.

try:
    import builtins as __builtin__
except ImportError:
    import __builtin__

def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
    if (name == "thisown"):
        return self.this.own(value)
    if (name == "this"):
        if type(value).__name__ == 'SwigPyObject':
            self.__dict__[name] = value
            return
    method = class_type.__swig_setmethods__.get(name, None)
    if method:
        return method(self, value)
    if (not static):
        if _newclass:
            object.__setattr__(self, name, value)
        else:
            self.__dict__[name] = value
    else:
        raise AttributeError("You cannot add attributes to %s" % self)


def _swig_setattr(self, class_type, name, value):
    return _swig_setattr_nondynamic(self, class_type, name, value, 0)


def _swig_getattr(self, class_type, name):
    if (name == "thisown"):
        return self.this.own()
    method = class_type.__swig_getmethods__.get(name, None)
    if method:
        return method(self)
    raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name))


def _swig_repr(self):
    try:
        strthis = "proxy of " + self.this.__repr__()
    except __builtin__.Exception:
        strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)

try:
    _object = object
    _newclass = 1
except __builtin__.Exception:
    class _object:
        pass
    _newclass = 0


def fact(arg1):
    return _example.fact(arg1)
fact = _example.fact

def my_mod(n, m):
    return _example.my_mod(n, m)
my_mod = _example.my_mod
# This file is compatible with both classic and new-style classes.

cvar = _example.cvar

1 个答案:

答案 0 :(得分:0)

-fpic可能从gcc中丢失,但这是一个VS2017 64位解决方案,作为使用Python 3.6(64位版本的编译器和Python)的有效示例。

使用准确的example.iexample.c

C:\example>swig -python example.i

C:\example>cl /MD /LD /W3 /Ic:\python36\include /Fe_example.pyd example_wrap.c example.c /link /libpath:c:\python36\libs
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

example_wrap.c
example.c
Generating Code...
Microsoft (R) Incremental Linker Version 14.16.27027.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/dll
/implib:_example.lib
/out:_example.pyd
/libpath:c:\python36\libs
example_wrap.obj
example.obj
   Creating library _example.lib and object _example.exp

C:\example>py
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> example.cvar.My_variable
3.0
>>> example.fact(3)
6
>>> example.my_mod(7,2)
1

您还可以使用distutils并创建setup.pyref

from distutils.core import setup, Extension

example_module = Extension('_example',
                           sources=['example.i', 'example.c'],
                           )

setup (name = 'example',
       version = '0.1',
       author      = "SWIG Docs",
       description = """Simple swig example from docs""",
       ext_modules = [example_module],
       py_modules = ["example"],
       )

命令:

py setup.py build_ext --inplace