Manufaturação industrial
Internet das coisas industrial | Materiais industriais | Manutenção e reparo de equipamentos | Programação industrial |
home  MfgRobots >> Manufaturação industrial >  >> Industrial programming >> python

Programação de Extensões Python com C: Criando Módulos Nativos Rápidos

Código escrito em linguagens compiladas (C, C++, Java) pode ser integrado ao Python como extensões. Um módulo de extensão é uma biblioteca C normal: .so (Unix) ou .dll (Windows).

Pré-requisitos

Estrutura de uma Extensão

Quatro partes:

  1. Inclusão de Python.h.
  2. Funções C a expor.
  3. Tabela de mapeamento de métodos (PyMethodDef).
  4. Função de inicialização (initModulo).

Header Python.h

Deve ser o primeiro include. Fornece API interna para integrar o módulo ao interpretador.

Funções C

Assinaturas padrão (retornam PyObject*):

static PyObject* MinhaFuncao(PyObject* self, PyObject* args);
static PyObject* MinhaFuncaoComKw(PyObject* self, PyObject* args, PyObject* kw);
static PyObject* MinhaFuncaoSemArgs(PyObject* self);

Use Py_RETURN_NONE para retornar None.

Nomes internos podem ser quaisquer (são static). Convenção: modulo_funcao.

Tabela de Mapeamento de Métodos

Array de PyMethodDef terminado por sentinela {NULL, NULL, 0, NULL}:

struct PyMethodDef {
    char* ml_name;       // nome visto no Python
    PyCFunction ml_meth; // ponteiro para função C
    int ml_flags;        // METH_VARARGS, METH_KEYWORDS, METH_NOARGS
    char* ml_doc;        // docstring (pode ser NULL)
};

Exemplo

static PyMethodDef modulo_metodos[] = {
    {"funcao", (PyCFunction)modulo_funcao, METH_NOARGS, NULL},
    {NULL, NULL, 0, NULL}
};

Função de Inicialização

Nome obrigatório: initModulo (onde Modulo é o nome do módulo). Exportada via PyMODINIT_FUNC.

PyMODINIT_FUNC initModulo(void) {
    Py_InitModule3("Modulo", modulo_metodos, "docstring do módulo");
}

Exemplo Completo: helloworld

#include 

static PyObject* helloworld(PyObject* self) {
    return Py_BuildValue("s", "Olá, extensões Python!!");
}

static char helloworld_docs[] = "helloworld(): Qualquer mensagem.\n";

static PyMethodDef helloworld_funcs[] = {
    {"helloworld", (PyCFunction)helloworld, METH_NOARGS, helloworld_docs},
    {NULL}
};

PyMODINIT_FUNC inithelloworld(void) {
    Py_InitModule3("helloworld", helloworld_funcs, "Módulo de extensão exemplo!");
}

Salve como hello.c.

Compilação e Instalação com distutils

setup.py:

from distutils.core import setup, Extension
setup(name='helloworld', version='1.0',
      ext_modules=[Extension('helloworld', ['hello.c'])])

Comando:

$ python setup.py install

(No Unix, pode exigir sudo.)

Importando a Extensão

#!/usr/bin/python
import helloworld
print(helloworld.helloworld())
Olá, extensões Python!!

Passando Parâmetros

Use assinatura METH_VARARGS e PyArg_ParseTuple para extrair argumentos.

static PyObject* modulo_funcao(PyObject* self, PyObject* args) {
    int i; double d; char* s;
    if (!PyArg_ParseTuple(args, "ids", &i, &d, &s))
        return NULL;
    // faça algo
    Py_RETURN_NONE;
}

Chamadas Python equivalentes:

modulo.funcao(1, s="tres", d=2.0)
modulo.funcao(i=1, d=2.0, s="tres")
modulo.funcao(s="tres", d=2.0, i=1)

Códigos de Formato para PyArg_ParseTuple

CódigoTipo CSignificado
ccharString Python de tamanho 1 → char C.
ddoubleFloat Python → double C.
ffloatFloat Python → float C.
iintInt Python → int C.
llongInt Python → long C.
Llong longInt Python → long long C.
OPyObject*Referência emprestada não-NULL.
schar*String Python (sem nulos) → char* C.
s#char*+intQualquer string Python → endereço e comprimento.
zchar*Como s, mas aceita None (define NULL).
|–Argumentos seguintes são opcionais.
:–Fim do formato, seguido de nome da função para mensagens de erro.
;–Fim do formato, seguido de mensagem de erro completa.

Retornando Valores com Py_BuildValue

Similar a PyArg_ParseTuple, mas passa valores reais (não endereços).

Exemplo: Função add

static PyObject* foo_add(PyObject* self, PyObject* args) {
    int a, b;
    if (!PyArg_ParseTuple(args, "ii", &a, &b))
        return NULL;
    return Py_BuildValue("i", a + b);
}

Equivalente Python:

def add(a, b):
    return a + b

Retornando Múltiplos Valores (tupla/lista/dict)

static PyObject* foo_add_sub(PyObject* self, PyObject* args) {
    int a, b;
    if (!PyArg_ParseTuple(args, "ii", &a, &b))
        return NULL;
    return Py_BuildValue("ii", a + b, a - b);  // tupla
}

Python: def add_sub(a,b): return (a+b, a-b)

Códigos Comuns de Py_BuildValue

CódigoTipo CSignificado
ccharchar C → string Python tamanho 1.
ddoubledouble C → float Python.
ffloatfloat C → float Python.
iintint C → int Python.
llonglong C → int Python.
NPyObject*Passa objeto Python e rouba referência.
OPyObject*Passa objeto Python e incrementa refcount.
schar*char* terminado em null → string Python (NULL → None).
s#char*+intchar* + comprimento → string Python.
(...)conforme ...Constrói tupla Python a partir de valores C.
[...]conforme ...Constrói lista Python.
{...}conforme ...Constrói dicionário (chaves e valores alternados).

Exemplo: Py_BuildValue("{issi}", 23, "zig", "zag", 42) → {23: 'zig', 'zag': 42}.

python

  1. Dominando Programação Orientada a Objetos em Python: Classes, Herança, Encapsulamento e Polimorfismo
  2. Função Print() do Python: Guia Prático com Exemplos
  3. Dominando o Método strip() do Python: Guia Completo e Exemplos Práticos
  4. Domine o str.count() do Python: Como Contar Caracteres e Substrings com Exemplos
  5. Domine Strings format() em Python com Exemplos Claros
  6. Domine o Método String.find() do Python: Sintaxe, Exemplos e Alternativas
  7. Dominando Funções Lambda em Python: Exemplos Práticos e Boas Práticas
  8. Função round() em Python Explicada com Exemplos Práticos
  9. Dominando a Função map() do Python: Sintaxe, Exemplos e Boas Práticas
  10. Python timeit(): Medindo Tempo de Execução com Exemplos Práticos