Calling a C function with gmp library included from a Python code

Viewed 71

I am trying to send a string from a function implemented in Python to a function implemented in C, perform some operations using GMP library and return a string to the function implemented in python. Details of code given below:

myModule.c file:



#include<Python.h>
#include<gmp.h>


 
char* Cnumfunc(char* n)
{

    printf("This is the string %s\n",n);
    mpz_t p1;
    mpz_init(p1);
    mpz_set_str(p1,n,10);
    gmp_printf("Value of the gmp number is : %Zd \n", p1);
    mpz_add_ui(p1,p1,1);//so now p1=11
    char retstr[100];//create a buffer of large size
    mpz_get_str(retstr,10,p1);

    return retstr;//Should return "11"
}
 
static PyObject* numfunc(PyObject* self, PyObject* args)
{
    char* n;
 
    if (!PyArg_ParseTuple(args, "s", &n))
        return NULL;
 
    return Py_BuildValue("s", Cnumfunc(n));
}

 
static PyMethodDef myMethods[] = {
    {"numfunc", numfunc, METH_VARARGS, "Calculate the numfunc"},
    {NULL, NULL, 0, NULL}
};
 
static struct PyModuleDef myModule = {
    PyModuleDef_HEAD_INIT,
    "myModule", //#name of module.
    "numfunc Module",
    -1,
    myMethods
};

PyMODINIT_FUNC PyInit_myModule(void)
{
    return PyModule_Create(&myModule);
}

Now setup.py file:

from distutils.core import setup, Extension
 
module = Extension('myModule', sources = ['myModule.c'])
 
setup (name = 'PackageName',
        version = '1.0',
        description = 'This is a package for myModule',
        ext_modules = [module])

And finally the test.py file:

import myModule
a=myModule.numfunc("10")
print(a)

Now I run

python3 setup build

And then I copy the myModule.cpython-38-x86_64-linux-gnu.so file in the build directory to the directory which contains test.py and then do

python3 test.py

This gives the error:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import myModule
ImportError: /home/aghosh/pybind/myModule.cpython-38-x86_64-linux-gnu.so: undefined symbol: __gmpz_set_str

I am really new to this kind of coding involving multiple languages and it will be very helpful if anyone has a solution to this problem

0 Answers
Related