zoukankan      html  css  js  c++  java
  • Python C扩展

    可以用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 ", PyInt_AsLong(obj));
      }
      else if(PyFloat_CheckExact(obj))
      {
        printf("obj is Float: %f ", PyFloat_AsDouble(obj));
      }
      else if(PyString_CheckExact(obj))
      {
        printf("obj is string:%s ", PyString_AsString(obj));
      }
      else if(PyList_CheckExact(obj))
      {
        printf("obj is list ");
        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 ");
        while (PyDict_Next(obj, &pos, &key, &subObj))
        {
          Print_PyObject(subObj);
        }
      }
    }
    static PyObject *PyExt_Set(PyObject *self, PyObject *args)
    {
      printf("PyExt_set! ");
      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 ", 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了。

     

  • 相关阅读:
    从产品原型到交互设计的过渡——初学者心得
    谈什么是卡片式设计?
    vertical-align:middle的居中细节调整
    line-height:2和line-height:2em的区别,它们是有区别的
    css中!important的用法总结
    使用em为单位制作两列弹性布局
    如何动态修改下拉列表的默认选中项
    【转】深入浅出协议栈
    经典排序js实现
    js 数组的拷贝
  • 原文地址:https://www.cnblogs.com/fellow1988/p/6193391.html
Copyright © 2011-2022 走看看