zoukankan      html  css  js  c++  java
  • windows下python调用c文件流程

    1.新建fun.c文件和fun.h文件

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int fac(int n)
    {
        if(n < 2)
            return 1;
         return n * fac(n-1);
    }
    
    char *reverse(char *s)
    {
        char t, *p = s,*q=(s+(strlen(s)-1));
    
        while(s && (p<q)){
            t = *p;
            *p++ = *q;
            *q-- = t;
        }
        return s;
    }
    
    int test(void)
    // int main(void)
    {
        char s[1024];
        printf("4!==%d
    ",fac(4));
        printf("8!==%d
    ",fac(8));
    
        strcpy(s,"arthas");
        printf("reversing 'arthas',we get '%s'
    ",reverse(s));
        return 0;
    }
    
    #ifndef FUN_H_
    #define FUN_H_
    
    int fac(int n);
    char *reverse(char *s);
    int test(void);
    
    #endif
    

    2.新建funwrapper.c文件

    #include "Python.h"
    #include <stdlib.h>
    #include <string.h>
    #include "fun.h"
    
    static PyObject *fun_fac(PyObject *self,PyObject *args)
    {
    	int num;
    	if(!PyArg_ParseTuple(args,"i",&num))
    		return NULL;
    	return (PyObject*)Py_BuildValue("i",fac(num));
    }
    
    static PyObject *fun_reverse(PyObject *self,PyObject *args)
    {
    	char *src;
    	char *mstr;
    	PyObject *retval;
    	if(!PyArg_ParseTuple(args,"s",&src))
    		return NULL;
    	mstr = malloc(strlen(src)+1);
    	strcpy(mstr,src);
    	reverse(mstr);
    	retval = (PyObject*)Py_BuildValue("ss",src,mstr);
    	free(mstr);
    	return retval;
    }
    
    static PyObject *fun_test(PyObject *self,PyObject *args)
    {
    	return (PyObject*)Py_BuildValue("i",test());
    }
    
    static PyMethodDef funMethods[] = {
    	{"fac",fun_fac,METH_VARARGS},
    	{"reverse",fun_reverse,METH_VARARGS},
    	{"test",fun_test,METH_VARARGS},
    	{NULL,NULL},
    };
    
    void initfun(void)
    {
    	Py_InitModule("fun",funMethods);
    }
    

    3.CMD使用指令

    setup.py install build
    

    这里我出错了python Unable to find vcvarsall.bat 错误,
    参考上一篇日志python Unable to find vcvarsall.bat 错误解决方法。解决了。
    然后生成出fun.pyd文件
    4.复制到python的DLLS文件夹下
    5.可以用python调用了

    import fun
    
    print fun.fac(4)
    print fun.reverse("arthas")
    fun.test()
    

    6.输出的结果
    ···
    24
    ('arthas', 'sahtra')
    4!24
    8!
    40320
    reversing 'arthas',we get 'sahtra'
    ···

  • 相关阅读:
    KM算法(带权二分图最优匹配)
    I'm Telling the Truth(二分图最大匹配) HDU
    过山车(二分图匹配裸题) HDU
    locker(dp) HDU
    Hunters(期望,数学) HDU
    Sum of divisors(进制转换) HDU
    DataTable 内数据搜索
    NPOI 读取xls,xlsx文件
    (转)C#将多个DLL集成到EXE文件中的方法
    saveFileDialog简单使用
  • 原文地址:https://www.cnblogs.com/Mysterious/p/7529228.html
Copyright © 2011-2022 走看看