在Ubuntu系统中,Python和C++可以通过多种方式进行交互。以下是两种常见的方法:
步骤如下:
a. 创建一个C/C++源文件,例如example.cpp
,并实现你想要从Python调用的函数。例如:
#include <Python.h>
static PyObject* hello(PyObject* self, PyObject* args) {
printf("Hello from C++!\n");
Py_RETURN_NONE;
}
static PyMethodDef ExampleMethods[] = {
{"hello", hello, METH_VARARGS, "Prints 'Hello from C++!'"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef examplemodule = {
PyModuleDef_HEAD_INIT,
"example",
NULL,
-1,
ExampleMethods
};
PyMODINIT_FUNC PyInit_example(void) {
return PyModule_Create(&examplemodule);
}
b. 使用setuptools
创建一个Python模块。创建一个名为setup.py
的文件,内容如下:
from setuptools import setup, Extension
module = Extension('example', sources=['example.cpp'])
setup(name='Example',
version='1.0',
description='This is a demo package',
ext_modules=[module])
c. 在终端中运行以下命令来编译C++代码并生成Python模块:
python setup.py build_ext --inplace
d. 现在你可以在Python代码中导入并使用C++函数了:
import example
example.hello()
步骤如下:
a. 安装Cython:
pip install cython
b. 创建一个名为example.pyx
的文件,内容如下:
cdef extern from "example.h":
void hello()
def hello_from_cython():
hello()
这里,我们声明了一个外部C++函数hello()
,并在Cython代码中调用它。
c. 创建一个名为example.h
的头文件,包含C++函数的声明:
#ifndef EXAMPLE_H
#define EXAMPLE_H
void hello();
#endif // EXAMPLE_H
d. 创建一个名为example.cpp
的源文件,实现C++函数:
#include <iostream>
#include "example.h"
void hello() {
std::cout << "Hello from C++!" << std::endl;
}
e. 创建一个名为setup.py
的文件,内容如下:
from setuptools import setup
from Cython.Build import cythonize
setup(
name='Example',
ext_modules=cythonize("example.pyx"),
include_dirs=[],
)
f. 在终端中运行以下命令来编译Cython代码并生成Python模块:
python setup.py build_ext --inplace
g. 现在你可以在Python代码中导入并使用C++函数了:
import example
example.hello_from_cython()
这两种方法都可以实现Python和C++之间的交互。选择哪种方法取决于你的需求和编程风格。