|
发表于 2023-2-3 19:05:15
|
显示全部楼层
本帖最后由 人造人 于 2023-2-3 19:06 编辑
首先,看看这个吧
https://github.com/ruby-china/Ho ... ter/README-zh_CN.md
然后,下面是一个简单的演示
参考
https://docs.python.org/zh-cn/3/extending/extending.html
https://docs.python.org/zh-cn/3/extending/building.html#building
- sh-5.1$ ls
- main.py spam.c
- sh-5.1$ cat spam.c
- #define PY_SSIZE_T_CLEAN
- #include <Python.h>
- #include <stdlib.h>
- static PyObject *spam_system(PyObject *self, PyObject *args) {
- const char *command;
- if(!PyArg_ParseTuple(args, "s", &command)) return NULL;
- int ret = system(command);
- return PyLong_FromLong(ret);
- }
- static PyMethodDef methods[] = {
- {"system", spam_system, METH_VARARGS, "Execute a shell command."},
- {NULL, NULL, 0, NULL}
- };
- static struct PyModuleDef spammodule = {
- PyModuleDef_HEAD_INIT,
- "spam",
- NULL,
- -1,
- methods
- };
- PyObject *PyInit_spam(void) {
- return PyModule_Create(&spammodule);
- }
- sh-5.1$ cat main.py
- #!/usr/bin/env python
- #coding=utf-8
- import spam
- spam.system('ls')
- spam.system("echo 'hello world!'")
- sh-5.1$ gcc -g -Wall -shared -I /usr/include/python3.10 -o spam.so spam.c
- sh-5.1$ ls
- main.py spam.c spam.so
- sh-5.1$ ./main.py
- main.py spam.c spam.so
- hello world!
- sh-5.1$
复制代码 |
|