首页 > 解决方案 > 使用 Python 代码中包含的 gmp 库调用 C 函数

问题描述

我正在尝试将一个字符串从一个用 Python 实现的函数发送到一个用 C 实现的函数,使用 GMP 库执行一些操作并将一个字符串返回给用 python 实现的函数。代码的详细信息如下:

myModule.c 文件:



#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);
}

现在 setup.py 文件:

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])

最后是 test.py 文件:

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

现在我跑

python3 setup build

然后我将构建目录中的 myModule.cpython-38-x86_64-linux-gnu.so 文件复制到包含 test.py 的目录中,然后执行

python3 test.py

这给出了错误:

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

我对这种涉及多种语言的编码真的很陌生,如果有人能解决这个问题,那将非常有帮助

标签: pythonc

解决方案


推荐阅读