无法 运行 python 痛饮教程

can't run swig tutorial for python

我尝试 运行 swig python 教程无济于事,我检查了很多类似的问题但是 none 解决了我的问题,我正在使用

windows *, 64 位

SWIG 版本 4.0.2

使用 i686-w64-mingw32-g++ [i686-w64-mingw32] 编译

配置选项:+pcre

该示例特别涉及用 C 编写的 gcd 函数;

/* File : example.c */

/* A global variable */
double Foo = 3.0;

/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
  int g;
  g = y;
  while (x > 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
}
/* File: example.i */
%module example

extern int gcd(int x, int y);
extern double Foo;

我运行swig -python example.i

但每当我运行gcc -c -fpic example.c -IC:\Users\Moses\anaconda3\include

example_wrap.c: In function '_wrap_gcd':
example_wrap.c:2886:17: warning: implicit declaration of function 'gcd'; did you mean 'gcvt'? [-Wimplicit-function-decla
ration]
   result = (int)gcd(arg1,arg2);
                 ^~~
                 gcvt
example_wrap.c: In function 'Swig_var_Foo_set':
example_wrap.c:2901:5: error: 'Foo' undeclared (first use in this function)
     Foo = (double)(val);
     ^~~
example_wrap.c:2901:5: note: each undeclared identifier is reported only once for each function it appears in
example_wrap.c: In function 'Swig_var_Foo_get':
example_wrap.c:2912:37: error: 'Foo' undeclared (first use in this function)
   pyobj = SWIG_From_double((double)(Foo));

我只得到 example.o 文件,而缺少 example_wrap.o 文件,几乎肯定是因为错误,我还是尝试用 ld -shared example.o /c/users/moses/Anaconda3/python37.dll /c/Windows/System32/msvcr120.dll -o _example.pyd 编译它 但是在尝试导入 example.py 文件时,出现以下错误:

Traceback (most recent call last):

  File "C:\Users\moses\cGraphy.py", line 1, in <module>
    import example

  File "C:/Users/moses/example.py", line 15, in <module>
    import _example

ImportError: dynamic module does not define module export function (PyInit__example)

非常感谢任何帮助,谢谢。

您的 example.i 文件需要将导出添加到包装器,并由 SWIG 处理它们:

%module example

// this section is copied directly into the generated wrapper, so the functions
// can be found when example_wrap.c is linked with example.c
%{
extern int gcd(int x, int y);
extern double Foo;
%}

// This tells SWIG to write wrappers for these exports.
extern int gcd(int x, int y);
extern double Foo;

如果不想重复定义,也可以使用:

%module example

// inline inserts into wrapper *and* SWIG wraps it.
%inline %{
extern int gcd(int x, int y);
extern double Foo;
%}

示例example.i:

>>> import example
>>> example.cvar.Foo
3.0
>>> example.gcd(35,14)
7

我使用 MSVC 而不是 gcc,使用这些命令:

swig -python example.i
cl /LD /W3 /Fe_example.pyd /Ic:\python39\include example_wrap.c example.c -link /libpath:c:\python39\libs