|
|
发表于 2019-11-22 21:06:16
|
显示全部楼层
- #include <Python.h>
- #include <iostream>
- PyObject *add(PyObject *self, PyObject *args)
- {
- int x, y;
- if(!PyArg_ParseTuple(args, "ii", &x, &y))
- return NULL;
- return Py_BuildValue("i", x + y);
- }
- PyObject *sub(PyObject *self, PyObject *args)
- {
- int x, y;
- if(!PyArg_ParseTuple(args, "ii", &x, &y))
- return NULL;
- return Py_BuildValue("i", x - y);
- }
- PyObject *print(PyObject *self, PyObject *args)
- {
- char *str;
- if(!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- std::cout << str << std::endl;
- return PyBool_FromLong(1);
- }
- static PyMethodDef hello_methods[] = {
- {"add", add, METH_VARARGS, "add function"},
- {"sub", sub, METH_VARARGS, "sub function"},
- {"print", print, METH_VARARGS, "print function"},
- {NULL, NULL, 0, NULL}
- };
- static PyModuleDef hello_module = {
- PyModuleDef_HEAD_INIT,
- "hello module",
- NULL,
- -1,
- hello_methods,
- NULL,
- NULL,
- NULL,
- NULL
- };
- PyMODINIT_FUNC PyInit_hello()
- {
- return PyModule_Create(&hello_module);
- }
复制代码
- g++ -fPIC -shared hello.cpp -I/usr/include/python3.8 -o hello.so
复制代码
参考
https://blog.csdn.net/zong596568821xp/article/details/81133511
linux下我试了,没问题
windows下我还没有试
|
|