Open In App

Calling Python from C | Set 2

Last Updated : 27 Mar, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Calling Python from C | Set 1

A reference to an existing Python callable needs to be passed in, to use this function. To do that there are many ways like – simply writing C code to extract a symbol from an existing module or having a callable object passed into an extension module.

Code #1 : Simple embedding example




int main()
{
    PyObject * pow_func;
    double x;
    Py_Initialize();
      
    // Get a reference to the math.pow function
    pow_func = import_name("math", "pow");
      
    // Call it using our call_func() code 
    for (x = 0.0; x < 10.0; x += 0.1)
    {
        printf("% 0.2f % 0.2f\n", x, call_func(pow_func, x, 2.0));
    }
          
    Py_DECREF(pow_func);
    Py_Finalize();
    return 0;
}


 
To build this last example, C needs to be compiled and link against the Python interpreter. The snippet below shows how to do it (this is something that might require some amount of fiddling with on your machine):

Code #2 :




all::
cc -g embed.c -I/usr/local/include/python3.3m \
-L /usr/local/lib/python3.3/config-3.3m -lpython3.3m


Compiling and running the resulting executable gives output as :

0.00 0.00
0.10 0.01
0.20 0.04
0.30 0.09
0.40 0.16
...

 
There is another example given by the code below that shows an extension function that receives a callable and some arguments and passes them to call_func() for the purposes of testing.

Code #3 :




/* Extension function for testing the C-Python callback */
  
PyObject * py_call_func(PyObject * self, PyObject * args)
{
    PyObject * func;
  
    double x, y, result;
    if (! PyArg_ParseTuple(args, "Odd", &func, &x, &y))
    {
        return NULL;
    }
    result = call_func(func, x, y);
    return Py_BuildValue("d", result);
}


 
Code #4 : Testing the extension function




import work
  
def add(x, y):
    return x + y
  
work.call_func(add, 3, 4)


Output :

7.0

 
It is critical that first we need to have a Python object representing the callable that is to be invoked. This could be a function, class, method, built-in method, or anything that implements the __call__() operation. To verify whether it is a callable function use PyCallable_Check().

Code #5 : Checking PyCallable_Check() function




double call_func(PyObject *func, double x, double y)
{
    ...
    // Verify that func is a proper callable
    if (!PyCallable_Check(func))
    {
        fprintf(stderr, "call_func: expected a callable\n");
        goto fail;
    }
    ...


 
Simply use PyObject_Call() to call a function, supplying it with the callable object, a tuple of arguments, and an optional dictionary of keyword arguments.

Py_BuildValue() can be used to build the argument tuple or dictionary.

Code #6 :




double call_func(PyObject *func, double x, double y)
    {
        PyObject *args;
        PyObject *kwargs;
          
        /* Build arguments */
        args = Py_BuildValue("(dd)", x, y);
        kwargs = NULL;
        /* Call the function */
        result = PyObject_Call(func, args, kwargs);
        Py_DECREF(args);
        Py_XDECREF(kwargs);
         
          
        /* Check for Python exceptions (if any) */
        if (PyErr_Occurred())
        {
            PyErr_Print();
            goto fail;
        }
          
    fail:
        PyGILState_Release(state);
        abort();
          
    }




Similar Reads

Calling Python from C | Set 1
In this article, we will mainly focus on safe execution of a Python callable from C, returning a result back to C and writing C code that needs to access a Python function as a callback. The code below focuses on the tricky parts that are involved in calling Python from C. Code #1 : [Step 1 and 2] Own the GIL and Verify that function is a proper ca
2 min read
Calling a Python function from MATLAB
We can call the Python functions and objects directly from MATLAB. To call Python functions from MATLAB, need to install a supported version of Python. MATLAB supports versions 2.7, 3.6, and 3.7 MATLAB loads Python when you type py.command. py.modulename.functionname Below examples shows how to call a user defined Python function from MATLAB. Examp
2 min read
Calling a Super Class Constructor in Python
Classes are like creating a blueprint for an object. If we want to build a building then we must have the blueprint for that, like how many rooms will be there, its dimensions and many more, so here the actual building is an object and blueprint of the building is a class. A Class is a user-defined data-type which has data members and member functi
4 min read
Calling another custom Python function from Pyspark UDF
PySpark, often known as Python API for Apache Spark, was created for distributed data processing. It gives users the ability to efficiently and scalable do complex computations and transformations on large datasets. User-Defined Functions (UDFs), which let users create their unique functions and apply them to Spark DataFrames or RDDs, which is one
7 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set method is to convert other type values to set this meth
7 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Interesting facts about strings in Python | Set 2 (Slicing)
Creating a String Strings in Python can be created using single quotes or double quotes or even triple quotes. # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'
4 min read
Creating a Proxy Webserver in Python | Set 2
Prerequisite: Creating a Proxy Webserver in Python - Set1 In this tutorial, a few interesting features are added to make it more useful. Add blacklisting of domains. For Ex. google.com, facebook.com. Create a list of BLACKLIST_DOMAINS in our configuration dict. For now, just ignore/drop the requests received for blacklisted domains. (Ideally, we mu
5 min read
Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
Prerequisite: Object-Oriented Programming in Python | Set 1 (Class, Object and Members) Data hiding In Python, we use double underscore (Or __) before the attributes name and those attributes will not be directly visible outside. Python Code class MyClass: # Hidden member of MyClass __hiddenVariable = 0 # A member method that changes # __hiddenVari
3 min read
Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase &amp; title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Article Tags :
Practice Tags :