## 5.1 Can I create my own functions in C? 

## EXTENDING/EMBEDDING FAQ 

## CHAPTER FIVE 

Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C. This is explained in the document extending-index. 

Most intermediate or advanced Python books will also cover this topic. 

## 5.2 Can I create my own functions in C++? 

Yes, using the C compatibility features found in C++. Place$_{extern "C" { ... }}$ around the Python include files and put$_{extern "C"}$ before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea. 

## 5.3 Writing C is hard; are there any alternatives? 

There are a number of alternatives to writing your own C extensions, depending on what you’re trying to do. 

Cython and its relative Pyrex are compilers that accept a slightly modified form of Python and generate the cor- responding C code. Cython and Pyrex make it possible to write an extension without having to learn Python’s C API. 

If you need to interface to some C or C++ library for which no Python extension currently exists, you can try wrapping the library’s data types and functions with a tool such as SWIG. SIP, CXX Boost, or Weave are also alternatives for wrapping C++ libraries. 

## 5.4 How can I execute arbitrary Python statements from C? 

The highest-level function to do this is$_{PyRun_SimpleString()}$ which takes a single string argument to be executed in the context of the module __main__ and returns $_{0}$for success and -1 when an exception oc- curred (including $_{SyntaxError}$). If you want more control, use PyRun_String() ; see the source for PyRun_SimpleString() in$_{Python/pythonrun.c}$ . 

