C++对python模块进行扩展

1) 使用的是C++python

2) 代码ios

#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文件python2.7

g++ -fpic -c -I/usr/include/python2.7 -I /usr/lib/python2.7/config example.cpp
g++ -shared -o example.so example.o函数

相关文章
相关标签/搜索