使用C语言扩展Python3

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用C语言扩展Python3相关的知识,希望对你有一定的参考价值。

使用C语言扩展Python3。
在Python3中正确调用C函数。

1. 文件demo.c

#include <Python.h>
 
// c function
static PyObject *
demo_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 PyObject *
demo_hello(PyObject *self, PyObject *args) {
    PyObject *name, *result;
    if (!PyArg_ParseTuple(args, "U:demo_hello", &name))
        return NULL;
    result = PyUnicode_FromFormat("Hello, %S!", name);
    return result;
}
 
static PyObject *
demo_chinese(PyObject *self, PyObject *args) {
    char *name;
    int age;
    if (!PyArg_ParseTuple(args, "si", &name, &age)) 
        return NULL;
    // printf("%d\n", age);
    char total[10000];
    memset(total, 0, sizeof(total));
    strcat(total, "strcat() 函数用来连接字符串:");
    strcat(total, "tset");
    PyObject *result = Py_BuildValue("s", total);
    return result;
}
 
// method table
static PyMethodDef DemoMethods[] = {
    {"system", // python method name
     demo_system, // matched c function name
     METH_VARARGS, /* a flag telling the interpreter the calling 
                                convention to be used for the C function. */
     "I guess here is description." },
 
     {"hello", demo_hello,  METH_VARARGS, "I guess here is description." },
     {"chinese", demo_chinese, METH_VARARGS, NULL },
     {NULL, NULL, 0, NULL}        /* Sentinel */
};
 
// The method table must be referenced in the module definition structure.
static struct PyModuleDef demomodule = {
    PyModuleDef_HEAD_INIT,
    "demo",   /* 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. */
    DemoMethods
};
 
// The initialization function must be named PyInit_name()
PyMODINIT_FUNC
PyInit_demo(void)
{
    return PyModule_Create(&demomodule);
}

2. hello.py

import demo
print("---------------------------")
status = demo.system("ls -l")
print("---------------------------")
hi = demo.hello("Sink")
print(hi)
print("---------------------------")
hi = demo.chinese("Sink", 2014)
print(hi)
print("---------------------------")

3. setup.py

from distutils.core import setup, Extension
 
module1 = Extension(demo,
                    sources = [demo.c])
 
setup (name = Demo hello,
       version = 1.0,
       description = This is a demo package by Sink,
       ext_modules = [module1])

 


以上是关于使用C语言扩展Python3的主要内容,如果未能解决你的问题,请参考以下文章

Python3快速入门(十七)——Python扩展模块开发

python C语言扩展之简单扩展-使用ctypes访问C代码

python怎么作为c语言的扩展

scrapy按顺序启动多个爬虫代码片段(python3)

详解python3如何调用c语言代码

学习笔记:python3,代码片段(2017)