python - 使用 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
我对这种涉及多种语言的编码真的很陌生,如果有人能解决这个问题,那将非常有帮助
解决方案
推荐阅读
- sql - PIVOT 汇总数据
- python - 从另一个 Python 文件导入类时出现问题
- swiftui - SwiftUI - 使用 @main 设置 rootViewController
- c# - 如何使用表适配器 C# SQL 更新 DataGridView 更改?
- mongodb - 为什么 $nin 比 $in 慢,Mongodb
- mongodb - 如何在mongodb查询中将数组转换为对象?
- javascript - 是什么导致函数在控制台中运行,但在事件侦听器调用时却没有?
- c# - 覆盖共享项目类中的属性
- javascript - 如何防止依赖项改变作为参数传入的对象而无需每次都重新克隆
- python - 打印哪个 Radio-ToggleButton 处于关闭状态