Skip to content

在c里调用python

Shuang0420 edited this page Jun 8, 2016 · 6 revisions

这一个例子是c调用了python的函数,函数返回值是list,包含了100个float值。

#include 
#include 
#include 
void test1(){
  Py_Initialize();//初始化python
  char *test = "奖励";
  PyObject * pModule = NULL;
  PyObject * pModule1 = NULL;
  PyObject * pFunc = NULL;
  PyObject * pArg    = NULL;
  PyObject * result;
  pModule = PyImport_ImportModule("inferSingleDocVec");//引入模块
  pFunc = PyObject_GetAttrString(pModule, "getDocVec");//直接获取模块中的函数
  pArg= Py_BuildValue("(s)", test);
  result = PyEval_CallObject(pFunc, pArg); //调用直接获得的函数,并传递参数;这里得到的是一个list
  for (int i = 0; i < PyList_Size(result); i++) {
    printf("%f\t", PyFloat_AsDouble(PyList_GetItem(result, (Py_ssize_t)i)));//打印每一个元素
  }
  //下面代码适用于返回值为字符串的情况
  //char* s=NULL;
  //PyArg_Parse(result, "s", &s); 
  //for (int i=0;s[i]!='\0';i++){
   // printf("%c",s[i]);
 // }
  Py_Finalize(); //释放python
//  return;
}
int main(int argc, char* argv[])
{
    test1();
    return 0;
}

编译运行

$ gcc -I/usr/local/lib/python2.7.11 -o inferDocVec inferDocVec.c -lpython2.7
$ ./inferDocVec

调用的inferSingleDocVec文件

#!/usr/bin/python
# -*- coding: utf-8 -*-
### for infer
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import gensim, logging
from gensim.models import Doc2Vec
import os
import jieba
import multiprocessing
import numpy as np
import base64
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

def getDocVec(doc_words):
    docwords=[word for word in jieba.cut(doc_words, cut_all = False)]
    model = Doc2Vec.load('all_model_v2.txt')
    invec = model.infer_vector(docwords, alpha=0.1, min_alpha=0.0001, steps=5)
    return (list)(invec)

关于如何将python文件转为模块,详见之前的一篇博文python 将自己写的py文件作为模块导入

参考链接

https://www.daniweb.com/programming/software-development/threads/237529/what-does-pyarg_parse-do-in-detail

http://stackoverflow.com/questions/5079570/writing-a-python-c-extension-how-to-correctly-load-a-pylistobject

[[TOC]]

Clone this wiki locally