【发布时间】:2017-05-21 04:24:02
【问题描述】:
我正在关注来自https://en.wikibooks.org/wiki/Python_Programming/Extending_with_C 的教程,我指的是标题为“使用 Swig”的部分。我在他的位置创建文件:
~/Desktop/TEST2/helloMODULEtest
我首先使用以下代码创建一个名为 hellomodule.c 的文件:
/*hellomodule.c*/
#include <stdio.h>
void say_hello(const char* name) {
printf("Hello %s!\n", name);
}
然后我在同一位置创建文件 hello.i:
/*hello.i*/
%module hello
extern void say_hello(const char* name);
我在 Pi 上安装了 swig 和 python-dev。所以在终端输入这三行:
$ swig -python hello.i
$ gcc -fpic -c hellomodule.c hello_wrap.c -I/usr/include/python2.7/
$ gcc -shared hellomodule.o hello_wrap.o -o _hello.so -lpython2.7
给我这些文件:
- hellomodule.o
- hello.py
- _hello.so
- hello_wrap.c
- hello_wrap.o
然后我 sudo 将 hello.py 和 _hello.so 复制到我的 python2.7 库文件中:
$ sudo cp ~/Desktop/TEST2/helloMODULEtest/hello.py /usr/lib/python2.7
$ sudo cp ~/Desktop/TEST2/helloMODULEtest/_hello.so /usr/lib/python2.7
在这些步骤之后,我可以使用 Python 2.7.9 shell。我在 shell 中输入
>>> import hello
并且没有收到任何警告或错误,这表明 hello.py 已被导入。但是,当我输入
>>> hello.say_hello("World")
该模块似乎没有返回任何内容并转到下一行。这是导入的“对话框”,并在我的下一个输入行中调用 hello:
>>> import hello
>>> hello.say_hello("World")
>>>
我想看看这个:
>>> import hello
>>> hello.say_hello("World")
Hello World!
>>>
那么,我的问题是为什么我的 hello.py 模块没有返回任何内容?
【问题讨论】:
-
您的函数可以直接打印到系统,
Python Shell会自动打印函数返回的值。你需要C而不是return而不是printf()才能看到Python Shell的结果 -
尝试直接在控制台运行它 -
python script.py然后也许你会在控制台看到你的文本。 -
上述建议均无效。如果我尝试
>>> print hello.say_hello("World")None会返回到我想查看Hello World!的位置。这是使用链接 [1] 中的代码完成的。 -
say_hello不使用return返回任何值,因此 pythonprint将不起作用。我很伤心say_hello使用printf(),它可能直接将文本发送到系统(Windows/Linux/Mac)而 Python 无法捕捉到它。将代码放入文件并直接在控制台/终端/cmd.exe/powershell 中运行文件,这样也许你会看到你的文本。
标签: python c linux module swig