Python调用C/C++

最后发布时间:2021-07-27 10:23:21 浏览量:

ctypes

sample c code

int max(int a)
{
    return a*3;
}

Compile

gcc -shared max.c -o max.so

python code

from ctypes import cdll
cur = cdll.LoadLibrary("./max.so")
a = cur.max(8)
print(a)

run

python main.py 

create an extension module called spam

import spam
spam.system("ls -l")

create a file named spammodule.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return PyLong_FromLong(sts);
}

static PyMethodDef SpamMethods[] = {

    {"system",  spam_system, METH_VARARGS,
     "Execute a shell command."},

    {NULL, NULL, 0, NULL}        /* Sentinel */
};

static struct PyModuleDef spammodule = {
    PyModuleDef_HEAD_INIT,
    "spam",   /* name of module */
    NULL, /* module documentation, may be NULL */
    -1,       /* size of per-interpreter state of the module,
                 or -1 if the module keeps state in global variables. */
    SpamMethods
};
PyMODINIT_FUNC
PyInit_spam(void)
{
    return PyModule_Create(&spammodule);
}

Compile spammodule.c file

gcc  -fPIC -shared spammodule.c -I/home/wangyang/anaconda3/include/python3.8 -o spam.so

This step can generate spam.so

create a python file named main.py and call c code

import spam
spam.system("ls -l")

just run python main.py

参考