[英]Calling C function from Python
我使用了一個用Python編寫的服務器文件來構建我的Raspberry Pi和我的iPhone之間的連接。 我寫了一個簡單的C程序,幫助翻譯莫爾斯代碼。 我想從Python服務器程序中調用C程序中的translate()
函數。
我在網上找到了一個教程並按照其說明編寫了我的C程序並編輯了netio_server.py
文件
在我的C程序morseCodeTrans.c
它就像
#include <Python.h>
#include <stdio.h>
static PyObject* py_translate(PyObject* self, PyObject* args)
{
char *letter;
PyArg_ParseTuple(args, "s", &letter);
if(strcmp(letter, ".-") == 0)
return Py_BuildValue("c", 'A');
else if(strcmp(letter, "-...") == 0)
return Py_BuildValue("c", 'B');
...
}
static PyMethodDef morseCodeTrans_methods[] = {
{"translate", py_translate, METH_VARARGS},
{NULL, NULL}
};
void initmorseCodeTrans()
{
(void)Py_InitModule("morseCodeTrans", morseCodeTrans_methods);
}
在服務器文件netio_server.py中它就像:
# other imports
import morseCodeTrans
...
tempLetter = ''
if line == 'short':
tempLetter += '.'
elif line == 'long':
tempLetter += '-'
elif line == 'shortPause':
l = morseCodeTrans.translate(tempLetter)
print "The letter is", l
以上是我稱之為C translate()
函數的唯一地方
然后我嘗試編譯morseCodeTrans.c
文件,如下所示:
gcc -shared -I/usr/include/python2.7/ -lpython2.7 -o myModule.so myModule.c
編譯成功了。 但是當我運行Python服務器程序時,無論何時它到達該行
l = morseCodeTrans.translate(tempLetter)
服務器程序剛剛終止,沒有任何錯誤消息。
我是Python編程的新手,所以我無法弄清楚問題出在哪里。 有幫助嗎?
你剛剛在界面中得到了一些小混合。 我按如下方式修改了代碼以使其工作:
#include <Python.h>
#include <stdio.h>
static PyObject* py_translate(PyObject* self, PyObject* args)
{
char *letter;
PyArg_ParseTuple(args, "s", &letter);
if(strcmp(letter, ".-") == 0)
return Py_BuildValue("c", 'A');
else if(strcmp(letter, "-...") == 0)
return Py_BuildValue("c", 'B');
/* ... */
else
Py_RETURN_NONE;
}
static PyMethodDef morseCodeTrans_methods[] = {
{"translate", py_translate, METH_VARARGS, ""},
{0}
};
PyMODINIT_FUNC initmorseCodeTrans(void)
{
Py_InitModule("morseCodeTrans", morseCodeTrans_methods);
}
使用distutils
構建更加安全,因為它可以防止您意外鏈接到錯誤版本的Python。 使用以下setup.py
:
from distutils.core import setup, Extension
module = Extension('morseCodeTrans', sources=['morseCodeTrans.c'])
setup(ext_modules=[module])
只需使用python setup.py install
。
編輯
盡管界面混亂,但看起來您的代碼仍然有效。 那么你的問題很可能是在鏈接過程中。 如上所述,使用distutils
應該可以解決這個問題。 如果你絕對想手動構建,請使用python-config --cflags
, python-config --ldflags
等來確保鏈接到正確版本的Python。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.