首页 > 技术文章 > Python C扩展

fellow1988 2016-12-17 22:42 原文

可以用C写一个module,可提供给Python使用。

#include <Python.h>
#include <stdio.h>
void Print_PyObject(PyObject *obj)
{
  Py_ssize_t size = 0;
  PyObject *subObj = NULL;
  PyObject *key = NULL;
  Py_ssize_t pos = 0;
  if (NULL == obj)
  {
    return;
  }
  if (Py_None == obj)
  {
    printf("obj is py_none");
  }
  else if(PyBool_Check(obj))
  {
    printf("obj is bool");
  }
  else if(PyInt_CheckExact(obj))
  {
    printf("obj is int : %ld\n", PyInt_AsLong(obj));
  }
  else if(PyFloat_CheckExact(obj))
  {
    printf("obj is Float: %f\n", PyFloat_AsDouble(obj));
  }
  else if(PyString_CheckExact(obj))
  {
    printf("obj is string:%s\n", PyString_AsString(obj));
  }
  else if(PyList_CheckExact(obj))
  {
    printf("obj is list\n");
    size = PyList_Size(obj);
    int idx = 0;
    for (idx = 0; idx < size; idx++)
    {
      subObj = PyList_GetItem(obj, idx);
      Print_PyObject(subObj);
    }
  }
  else if(PyList_CheckExact(obj))
  {
    printf("obj is dict\n");
    while (PyDict_Next(obj, &pos, &key, &subObj))
    {
      Print_PyObject(subObj);
    }
  }
}
static PyObject *PyExt_Set(PyObject *self, PyObject *args)
{
  printf("PyExt_set!\n");
  PyObject *newObject;
  const char *uri;
  if (!PyArg_ParseTuple(args, "sO!", &uri, &PyDict_Type, &newObject) &&
    !PyArg_ParseTuple(args, "sO!", &uri, &PyList_Type, &newObject))
  {
    return Py_BuildValue("i", -1);
  }
  printf("uri:%s\n", uri);

  return Py_BuildValue("i", 0);
}
static PyMethodDef PyExtMethods[] ={
  {"Set", PyExt_Set, METH_VARARGS, "Perform Set Operation"},
  {NULL, NULL, 0, NULL}
};
void initPyExt(void)
{
  //PyImport_AddModule("PyExt");
  Py_InitModule("PyExt", PyExtMethods);
}

在C module中会提供一个Set 方法。

然后编写setup.py

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

编译:python setup.py build

安装:python setup.py install

 

就可以在python中import PyExt了。

 

 

推荐阅读