OS
window10 64
python版本
python --version
Python 3.10.7
准备C++代码
tips
- demo里兼容了python2.x和python3.x
- 动态库名字为test,则初始化方法也必须为init_test/PyInit_test,否则会报:LINK : error LNK2001: 无法解析的外部符号 PyInit_xxx
- c++代码需要用extern "C" 修饰init函数,(其实此方式不支持C++,用C得方式调用了C++而已)
cpp/test.cpp
// Python includes
#include <Python.h>
int Add(int x, int y)
{
return x + y;
}
PyObject* WrappAdd(PyObject* self, PyObject* args)
{
int x, y;
if (!PyArg_ParseTuple(args, "ii", &x, &y))
{
return NULL;
}
return Py_BuildValue("i", Add(x, y));
}
//-----------------------------------------------------------------------------
static PyMethodDef test_methods[] = {
{"Add", WrappAdd, METH_VARARGS, "Add"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
//-----------------------------------------------------------------------------
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC init_test(void)
{
(void) Py_InitModule("test", test_methods);
}
#else /* PY_MAJOR_VERSION >= 3 */
static struct PyModuleDef test_module_def = {
PyModuleDef_HEAD_INIT,
"test",
"Internal \"test\" module",
-1,
test_methods
};
PyMODINIT_FUNC PyInit_test(void)
{
return PyModule_Create(&test_module_def);
}
#endif /* PY_MAJOR_VERSION >= 3 */
使用导出模块 setup.py
from distutils.core import setup, Extension
import io
long_description = io.open("[README.md](http://README.md)", encoding="utf-8").read()
module_device = Extension('test', sources = ['cpp/test.cpp'] )
setup (name = 'test-cpp2python',
version = '1.1.0',
description = 'test-cpp2python',
long_description=long_description,
long_description_content_type="text/markdown",
author='hcm',
url='',
license='MIT',
ext_modules = [module_device],
options={'build':{'build_lib':'./test'}},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Information Technology",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: C++",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Scientific/Engineering",
"Topic :: Software Development",
],)
导出python扩展模块
python setup.py build
查看生成的pyd文件
test/test.cp310-win_amd64.pyd
测试
cd test
python
>>> import test
>>> test.Add(1,2)
3