Extending the C language module in Python

Source: Internet
Author: User
Tags naming convention syslog

There is a previously written C language code, I want to use it in a Python program. I first read the method in the basic Python tutorial, which says that you can use swig with Python built-inDistutils module to implement the method. I tried the steps in the book and, as a result, always prompted "importerror:dynamic module does not define init function (initprintf)" When importing the module. At first I thought there was no lil bit location for so files. But I tried to create a simple Python module in the directory, and then import it, and found that there was no problem, it seems that Python can be directly imported into the current directory of the module . Then I went online to find other methods, found that few people on the internet with swig, most of them are to write wrap file implementation. But there is also a use of swig, in which the compilation steps are different from the book. I just tried that, and there was a new mistake, "Importerror:/example.so:undefined symbol:fact". It seems that the error before the book was due to the fact that the so file was not placed in the specified location. Then I began to find a way to solve the new mistake, toss for a while to consider whether it is not compiled, so I follow the method of another site manually compiled, the problem has finally been resolved. The solution comes from the IBM technology community, which seems to be a reliable site. Just now I have tried again on the method of the book. I found that swig is not a problem, the role of this tool is to convert the C source file into a Python interface source files. I then renamed the previously generated so file, preceded by _, then moved into the Python module folder and the problem was resolved. It seems that the swig mechanism is that the resulting so file must be stored in the specified folder with a fixed naming convention, or there will be a problem. It seems that swig is still not enough human ah. and then I started experimenting with myself writing wrap source files withThe Distutils implements the C extension. But it's still going to happen ."Importerror:./example.so:undefined symbol:fact". At this time I think back to my own online compiling tutorial, there is a step to the original C file is also compiled into, I just suddenly dawned,Distutils didn't compile the original C file, how can the related function be realized Ah! So I study setup.py found inside the source file is a list, should be able to fill in multiple source files, so I put the original source files are also filled in, sure enough the problem has been resolved. in summary, the expansion of the C language module in Python can be summarized in the following steps:
  1. First, write the C source file that contains the Py interface, called WRAP.C. This step can be used with swig. Example:swig-python foo.i
  2. Next, compile the wrap.c to generate xx.so. This step can be done using the  distutils. If you want to use   distutils words, You will need to write a PY script first. example: Setup (name = ' Example ', Version = ' 1.0 ', ext_modules = [Extension (' Example ', [' wrap.c ', ' Example.c '])   NOTE: The list in the sentence not only contains the wrap source file, but also the original source file of the function
  3. The so file in the previous step is the library file that can be used eventually, put the file into the lib of py or the current directory, you can import the C language Extension module for use. If you have used swig before, move the corresponding so file into the module folder and add _ to the file name. Example: CP printf.so/usr/lib64/python2.7/site-packages/_printf.so
After the previous study, I have been able to use the well-written wrap file to build the C extension library. Today I decided to compile my own functions into an extended library. Although I can easily use the swig implementation, but Swig requires the written library files must be placed in the specified directory, otherwise there is a problem, but I think that all the required libraries into a local directory to facilitate the porting of the program, Swig obviously contrary to my idea. So I decided to write my wrap file myself.
There are several key functions in the     wrap file that must be mastered. The first is: pyobject* wrap_fact (pyobject* self, pyobject* args). This function functions as a C function that parses the parameters that the python passes in and executes the response. Pyarg_parsetuple (args, "is", &n,&c) functions can be used to parse the (tuple) parameters that are passed in by Python. The string parameter is a formatted string with the is representation of the shape and string. The next need to add the storage parameters of the C variable address, it is important to note that these parameters must be used to store parameters of the address of the variable, even if you want to store a string is also the same, this is still a certain difference with scanf. Once the parameters have been parsed, the corresponding C functions can be called directly using the resulting parameters. You can then return a value to Python using return Py_buildvalue ("I", result). A hint in a statement can return the value of the result variable as an integer. In general, the function is to obtain the parameters that Python passes when invoking the corresponding function, then execute the C snippet in the function with these parameters, and then return the specified value in the C snippet to Python.     is an array of pointers: Static Pymethoddef examplemethods[]. This array is used to store the C function mapping table. Each C function needs to have one such {"Fact", Wrap_fact, Meth_varargs, "Caculate n!"} Array, where the elements in turn represent the names of functions in Python, interface function addresses, parameter types, function descriptions. How many functions need to be expanded to have the number of such arrays.     Finally, the module initialization function: void Initexample (). Note that the name of this function is fastidious and must be the Init module name. Inside, you need to include the statement: M = py_initmodule ("Example", Examplemethods), where the parameters represent the module name, the function map array, respectively.     Example:
#include <python.h>extern int sendsyslog (const char *addr,int port,int type), extern int sendtoac2 (int type); extern int sendtoac1 (int type), extern int rarecv (int wtime,const char *if_name2);  pyobject* Sendcmsg_syslog (pyobject* self, pyobject* args) {int port,type, result;  Char *addr; if (!  Pyarg_parsetuple (args, "SII", &addr,&port,&type)) return NULL;  result = Sendsyslog (Addr,port,type); Return Py_buildvalue ("I", result);}  pyobject* Sendcmsg_sendac1 (pyobject* self, pyobject* args) {int type, result; if (!  Pyarg_parsetuple (args, "I", &type)) return NULL;  result = Sendtoac1 (type); Return Py_buildvalue ("I", result);} Static Pymethoddef sendcmsgmethods[] ={{"Syslog", Sendcmsg_syslog, Meth_varargs, "Send Syslog msg!"}, {"Sendac1", SENDC MSG_SENDAC1, Meth_varargs, "send a Q msg to Client1"}, {"Sendac2", Sendcmsg_sendac2, Meth_varargs, "send a Q msg to Clien T2 "}, {" Rarecv ", Sendcmsg_rarecv, Meth_varargs," Detect RA Msg "}, {NULL, null}};void initsendcmsg (){pyobject* m; m = Py_initmodule ("sendcmsg", Sendcmsgmethods);}


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.