1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
// MyMath.cpp
#include "pch.h"
#include "Python.h"
double Add(double x, double y)
{
return x + y;
}
double Subtract(double x, double y)
{
return x - y;
}
double Multiply(double x, double y)
{
return x * y;
}
double Divide(double x, double y)
{
return x / y;
}
// 封装c++函数
PyObject* MyMath_Add(PyObject* self, PyObject* args)
{
double x, y;
if (!PyArg_ParseTuple(args, "dd", &x, &y))
{
return NULL;
}
return Py_BuildValue("d", Add(x, y));
}
PyObject* MyMath_Subtract(PyObject* self, PyObject* args)
{
double x, y;
if (!PyArg_ParseTuple(args, "dd", &x, &y))
{
return NULL;
}
return Py_BuildValue("d", Subtract(x, y));
}
PyObject* MyMath_Multiply(PyObject* self, PyObject* args)
{
double x, y;
if (!PyArg_ParseTuple(args, "dd", &x, &y))
{
return NULL;
}
return Py_BuildValue("d", Multiply(x, y));
}
PyObject* MyMath_Divide(PyObject* self, PyObject* args)
{
double x, y;
if (!PyArg_ParseTuple(args, "dd", &x, &y))
{
return NULL;
}
return Py_BuildValue("d", Divide(x, y));
}
static PyMethodDef MyMath_methods[] = {
{"add", MyMath_Add, METH_VARARGS, "This is an add function."},
{"subtract", MyMath_Subtract, METH_VARARGS, "This is a subtract function."},
{"multiply", MyMath_Multiply, METH_VARARGS, "This is a multiply function."},
{"divide", MyMath_Divide, METH_VARARGS, "This is a divide function."},
{NULL, NULL, 0, NULL}
};
static PyModuleDef MyMath_module = {
PyModuleDef_HEAD_INIT,
"MyMath",
"My Math Module",
0,
MyMath_methods
};
PyMODINIT_FUNC PyInit_MyMath()
{
return PyModule_Create(&MyMath_module);
}
|