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
- Headers do Python (
Python.h). No Unix, instale pacotepython3-dev; no Windows, vêm com o instalador binário. - Bom conhecimento de C/C++.
Estrutura de uma Extensão
Quatro partes:
- Inclusão de
Python.h. - Funções C a expor.
- Tabela de mapeamento de métodos (
PyMethodDef). - 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ódigo | Tipo C | Significado |
|---|---|---|
| c | char | String Python de tamanho 1 → char C. |
| d | double | Float Python → double C. |
| f | float | Float Python → float C. |
| i | int | Int Python → int C. |
| l | long | Int Python → long C. |
| L | long long | Int Python → long long C. |
| O | PyObject* | Referência emprestada não-NULL. |
| s | char* | String Python (sem nulos) → char* C. |
| s# | char*+int | Qualquer string Python → endereço e comprimento. |
| z | char* | 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ódigo | Tipo C | Significado |
|---|---|---|
| c | char | char C → string Python tamanho 1. |
| d | double | double C → float Python. |
| f | float | float C → float Python. |
| i | int | int C → int Python. |
| l | long | long C → int Python. |
| N | PyObject* | Passa objeto Python e rouba referência. |
| O | PyObject* | Passa objeto Python e incrementa refcount. |
| s | char* | char* terminado em null → string Python (NULL → None). |
| s# | char*+int | char* + 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
- Dominando Programação Orientada a Objetos em Python: Classes, Herança, Encapsulamento e Polimorfismo
- Função Print() do Python: Guia Prático com Exemplos
- Dominando o Método strip() do Python: Guia Completo e Exemplos Práticos
- Domine o str.count() do Python: Como Contar Caracteres e Substrings com Exemplos
- Domine Strings format() em Python com Exemplos Claros
- Domine o Método String.find() do Python: Sintaxe, Exemplos e Alternativas
- Dominando Funções Lambda em Python: Exemplos Práticos e Boas Práticas
- Função round() em Python Explicada com Exemplos Práticos
- Dominando a Função map() do Python: Sintaxe, Exemplos e Boas Práticas
- Python timeit(): Medindo Tempo de Execução com Exemplos Práticos