码迷,mamicode.com
首页 > 编程语言 > 详细

使用C语言扩展Python3

时间:2017-02-23 22:44:47      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:void   lag   erp   import   ati   setup.py   package   ems   字符   

使用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

标签:void   lag   erp   import   ati   setup.py   package   ems   字符   

原文地址:http://www.cnblogs.com/yaoyu126/p/6435912.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!