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函數

相關文章
相關標籤/搜索