zoukankan      html  css  js  c++  java
  • python下调用c语言代码

    1)首先,创建一个.c文件,其大体内容如下:

       2 #include <Python.h>

     99 char * extract(char * path)                                                   //想要调用的函数
    100 {
    112     char * Q = (char * )malloc(3*sizeof(char));
               。

               。

               。
    149     return Q;
    150 }
    151
    152
    153 PyObject* wrap_extract(PyObject* self, PyObject* args)           //与python的接口函数,python中实际上调用的是这个函数,由这个函数调用真正的函数
    154 {
    155       int n;
    156       char * path,*result;
    157       if (! PyArg_ParseTuple(args, "s:extract", &path))                //进行参数传递,把python中的参数转到c语言中
    158                 return NULL;
    159       result = extract(path);
    160       return Py_BuildValue("s", result);
    161 }
    162
    163 static PyMethodDef extractMethods[] =                            
    164 {
    165       {"extract", wrap_extract, METH_VARARGS, "by DChipNau"},
    166       {NULL, NULL}
    167 };
    168
    169 void initextract()                                                   //当import这个模块之后会调用这个函数。
    170 {
    171       PyObject* m;
    172       m = Py_InitModule("extract", extractMethods);
    173 }

    2)然后使用如下命令进行编译:

    gcc -fPIC extract.c -o extract.so -shared  -I/usr/include/python2.7 -I/usr/lib/python2.7/config

    3)在python中调用方法如下:

    import extract

    string = extract.extract(str(out_file))

    PS:参数传递时直接传递int数组真是相当难受

  • 相关阅读:
    2020 7 13 每日随笔
    2020 7 10 每日总结
    2020 7 14 每日总结
    2020 7 16 每日总结
    2020 7 15 每日总结
    2020 7 19 每日总结
    2020 7 18 每日总结
    2020 7 17 每日总结
    2020 7 11
    2020 7 12
  • 原文地址:https://www.cnblogs.com/dchipnau/p/5296728.html
Copyright © 2011-2022 走看看