您的位置:首页 > 编程语言 > C语言/C++

C++对python模块进行扩展

2016-05-17 00:00 246 查看
摘要: 与C开发有点区别.

1) 使用的是C++

2) 代码

#include <Python.h>
#include <stdio.h>
#include <iostream>

#ifdef _WIN32
#include "stdafx.h"
#include <Windows.h>
#else
#include <sys/stat.h>
#include <time.h>
#ifndef _MAX_PATH
#define _MAX_PATH 255
#endif
#endif

using namespace std;

static PyObject* wrap_decode_image(PyObject* self, PyObject* args)
{
// 2个参数
// 都是 Unicode 的字符串
char *xml_filepathname;
char *image_filepathname;
if (! PyArg_ParseTuple(args, "ss", &xml_filepathname,&image_filepathname))
return NULL;

printf("input xml path: %s \r\n", xml_filepathname);
printf("input image path: %s \r\n", image_filepathname);

string xml(xml_filepathname);
string image(image_filepathname);

return Py_BuildValue("s", xml_filepathname);
}

static PyMethodDef pyDiscernMethods[] =
{
{"decode_image", wrap_decode_image, METH_VARARGS,"decode code"},
{NULL, NULL}
};

//注意 C++ 需要使用 PyMODINIT_FUNC
// 否则 g++ 编译成功,import之后提示找不到initpydiscern函数

PyMODINIT_FUNC initpydiscern(){
Py_InitModule("pydiscern", pyDiscernMethods);
}

编译为so文件

g++ -fpic -c -I/usr/include/python2.7 -I /usr/lib/python2.7/config example.cpp
g++ -shared -o example.so example.o
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: