Python C Extension

Source: Internet
Author: User

You can write a module in C that you can use for 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);
}

A set method is provided in the C module.

Then write setup.py

From Distutils.core import Setup, Extension
Setup (name= ' Pyext ', version= ' 1.0 ', ext_modules=[extension (' Pyext ', sources=[' pyext.c ')])

Compiling: Python setup.py build

Installation: Python setup.py install

You can import pyext in Python.

Python C Extension

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.