一、写一个cpp

郴州网站制作公司哪家好,找创新互联建站!从网页设计、网站建设、微信开发、APP开发、响应式网站建设等网站项目制作,到程序开发,运营维护。创新互联建站成立与2013年到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联建站。
这个cpp的功能是 “加法器”,extern “C”的存在是因为python 的ctype可以调用C但是没有Cplustype~~~所以,~~~
#include "/home/oujie/anaconda3/envs/pytorch-master/include/python3.7m/Python.h"
#功能实现在这个函数中
extern "C"
int add_func(int a,int b)
{
return a+b;
}
#下面的这些是调用相关的API把数据格式进行转换,让python可以调用,这也是python的头文件里面的定义好的
extern "C"
static PyObject *_add_func(PyObject *self, PyObject *args)
{
int _a,_b;
int res;
if (!PyArg_ParseTuple(args, "ii", &_a, &_b))
return NULL;
res = add_func(_a, _b);
return PyLong_FromLong(res);
}
extern "C"
static PyMethodDef CppModuleMethods[] =
{
{
"add_func",
_add_func,
METH_VARARGS,
""
},
{NULL, NULL, 0, NULL}
};
extern "C"
PyMODINIT_FUNC initcpp_module(void)
{
(void) Py_InitModule("cpp_module", CppModuleMethods);
}二、对上面的这个CPP编译
#linux下面编译成so gcc -o add_demo.so -shared -fPIC add_demo.c #windows下编译成dll
三、写一个python文件调用
import ctypes
dll=ctypes.cdll.LoadLibrary
lib=dll("./add_demo.so")
print("python call cpp so:")
p=lib.add_func(2,3)
print(p)