C function call from Python

I used a server file that was written in Python to establish a connection between my Raspberry Pi and my iPhone. And I wrote a simple C program that helps translate morse code. I want to call a function translate()in C program from a Python server program.

I found the tutorial online and followed its instructions to write my C program and edit the file netio_server.py

In my C program, morseCodeTrans.cI like it.

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

And in the netio_server.py server file this is like:

# 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

Above is the only place I would call a C function translate()

Then I tried to compile the file morseCodeTrans.cas follows:

gcc -shared -I/usr/include/python2.7/ -lpython2.7 -o myModule.so myModule.c

The compilation was successful. But when I ran the Python server program, whenever it reached the line

l = morseCodeTrans.translate(tempLetter)

.

Python, , . ?

+4
1

. , :

#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.

Edit

, , - . . , distutils . , python-config --cflags, python-config --ldflags .., , Python.

+1

Source: https://habr.com/ru/post/1538520/


All Articles