Python 与 C++ 混合编程 实验

来源:互联网 发布:sql replace 替换空格 编辑:程序博客网 时间:2024/06/08 04:40

实验目的:

实现Python调用C++ 输入法 API的目的

实验环境:

Ubuntu Kylin 15.10
Python 2.7.9
GCC 4.9.2

实验过程:

开始的时候看到了一些C++与Python的混合编程,最终选用了拓展Python库的方案。并了解了一下Python的底层
(?)是否所有带有垃圾回收的语言的variable都是用的引用?

编(C)写(P):

wrapper.cpp

foo用于测试 return list
foo1用于测试形参类型

/**wrapper.cpp**/#include <Python.h>#include <cstdio>static PyObject * ex_foo(PyObject *self, PyObject *args){    printf("TYPE:%s\n",Py_TYPE(args)->tp_name);    // create the list    PyObject* pList = PyList_New(3); // new reference    assert(PyList_Check(pList));// set some initial values    for(int i = 0; i < 3; ++i)        PyList_SetItem(pList, i, Py_BuildValue("i", i));// insert an item    PyList_Insert(pList, 2, Py_BuildValue("s", "inserted"));// append an item    PyList_Append(pList, Py_BuildValue("s", "appended"));// sort the list    PyList_Sort(pList);// reverse the list    PyList_Reverse(pList);// fetch and manipulate a list slice    PyObject* pSlice = PyList_GetSlice(pList, 2, 4); // new reference    for(int j = 0; j < PyList_Size(pSlice); ++j)    {        PyObject *pValue = PyList_GetItem(pList, j);        assert(pValue);    }    Py_DECREF(pSlice);    return pList;}static PyObject * ex_foo1(PyObject *self, PyObject *args){    printf("PyTuple_Check:%d\n",(int)PyTuple_Check(args));    assert(PyTuple_Check(args));    printf("PyTupe_Size:%d\n",(int)PyTuple_Size(args) );    assert(PyTuple_Size(args) == 1);    char *s=NULL;    printf("s:%s\n",s);    printf("PyArg_ParseTuple:%d\n",(int)PyArg_ParseTuple(args, "s", &s));    if (!PyArg_ParseTuple(args, "s", &s))        PyErr_SetString(PyExc_TypeError, "invalid parameter");    Py_INCREF(args);    return args;}static PyMethodDef example_methods[] ={    {"foo", ex_foo, METH_VARARGS, "foo() doc string"},    {"foo1", ex_foo1, METH_VARARGS, "foo1() doc string"},    {NULL, NULL}};PyMODINIT_FUNC initexample(void){    Py_InitModule("example", example_methods);}

setup.py

python setup.py的用法
python setup.py的卸载方法

#!./setup.pyfrom distutils.core import setup, Extensionexample_mod = Extension('example', sources = ['wrapper.cpp'])setup(name = "example",    version = "1.0",    description = "A sample extension module",    ext_modules = [example_mod])

run.sh

#!./run.shpython setup.py install --record logecho "setup OVER"

执行

命令行中

>>> **@**:./test$ sudo sh run.sh[sudo] password for voodoo: running installrunning buildrunning build_extbuilding 'example' extensionx86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c wrapper.cpp -o build/temp.linux-x86_64-2.7/wrapper.occ1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++wrapper.cpp: In function ‘PyObject* ex_foo(PyObject*, PyObject*)’:wrapper.cpp:24:19: warning: unused variable ‘pValue’ [-Wunused-variable]         PyObject *pValue = PyList_GetItem(pList, j);                   ^c++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/wrapper.o -o build/lib.linux-x86_64-2.7/example.sorunning install_libcopying build/lib.linux-x86_64-2.7/example.so -> /usr/local/lib/python2.7/dist-packagesrunning install_egg_infoRemoving /usr/local/lib/python2.7/dist-packages/example-1.0.egg-infoWriting /usr/local/lib/python2.7/dist-packages/example-1.0.egg-infowriting list of installed files to 'log'setup OVER>>> **@**:./test$ python>>> from example import *>>> foo1("test")PyTuple_Check:1PyTupe_Size:1s:(null)PyArg_ParseTuple:1('test',)>>> foo1()PyTuple_Check:1PyTupe_Size:0s:(null)PyArg_ParseTuple:0()

我们可以用type(foo1)来查看返回值的类型。我便是这样知道的参数参数类型再上网查的,参数类型为tuple(元组)。
PyArg_ParseTuple参考。

0 0
原创粉丝点击