[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Example 20-4. PP4E\Integrate\Extend\HelloLib\hellolib.c


/*****



  • A simple C library file, with a single function, "message",

  • which is to be made available for use in Python programs.

  • There is nothing about Python here--this C function can be

  • called from a C program, as well as Python (with glue code).
    *****/


#include <string.h>
#include <hellolib.h>


static char result[1024]; / this isn't exported /


char
message(char
label) / this is exported /
{
strcpy(result, "Hello, "); / build up C string /
strcat(result, label); / add passed-in label /
return result; / return a temporary /
}


While you’re at it, define the usual C header file to declare the function externally, as
shown in Example 20-5. This is probably overkill for such a small example, but it will
prove a point.


Example 20-5. PP4E\Integrate\Extend\HelloLib\hellolib.h


/****



  • Define hellolib.c exports to the C namespace, not to Python

  • programs--the latter is defined by a method registration

  • table in a Python extension module's code, not by this .h;
    ****/


extern char message(char label);


Now, instead of all the Python extension glue code shown in the prior sections, simply
write a SWIG type declarations input file, as in Example 20-6.


Example 20-6. PP4E\Integrate\Extend\Swig\hellolib.i


/**



  • Swig module description file, for a C lib file.

  • Generate by saying "swig -python hellolib.i".
    **/


%module hellowrap


%{
#include <hellolib.h>
%}


extern char message(char); / or: %include "../HelloLib/hellolib.h" /
/ or: %include hellolib.h, and use -I arg /


1492 | Chapter 20: Python/C Integration

Free download pdf