python visual studio 在线编译_Visual Studio 2013 编译 64 位 Python 的 C 扩展 (使用 PyObject 包装)...

对于 32 位 Python 的 C 扩展,以前用过 mingW32 编译,

687c0fd3f9d0f2ee2be7add4b03462ad.png

但是 mingW32 不支持 64 位 Python 的 C 扩展编译,详情可见 stackoverflow,这位前辈的大意如下,

ae4a5e767c6c0a658e1857ff4a860bd0.png

以下介绍 Visual Studio 2013 编译 64 位 Python 的 C 扩展步骤:

1)准备 C 文件和包装文件,

ExtDemo.c

//Purpose: C code, for wrappered.

#include#include#include

int fact(intn)

{if(n < 2)return 1;return n * fact(n - 1);

}char * reverse(char *s)

{chart;char *p =s;char *q = (s + (strlen(s) - 1));while(p

{

t= *p;*p++ = *q;*q-- =t;

}returns;

}//just for unit test, for the two function above

int unit_test(void)

{//test fact()

printf("4! = %d\n", fact(4));

printf("8! = %d\n", fact(8));

printf("12! = %d\n", fact(12));//test reverse

char s[10] = "abcdef";

printf("reversing 'abcdef', we get '%s'\n", reverse(s));char s2[10] = "madam";

printf("reversing 'madam', we get '%s'\n", reverse(s2));return 0;

}

包装代码 ExtDemo_Wrapper.c

//Purpose: According to the C code, write the Wrapper.

#include"Python.h"

//function declaration

int fact(intn);char * reverse(char *s);int unit_test(void);static PyObject * ED_fact(PyObject * self, PyObject *args)

{intnum;if(!PyArg_ParseTuple(args, "i", &num))returnNULL;return (PyObject *)Py_BuildValue("i", fact(num));

}static PyObject * ED_reverse(PyObject * self, PyObject *args)

{char *orig_str;if (!PyArg_ParseTuple(args, "s", &orig_str))returnNULL;return (PyObject *)Py_BuildValue("s", reverse(orig_str));

}static PyObject * ED_unit_test(PyObject * self, PyObject *args)

{

unit_test();return (PyObject *)Py_BuildValue("");

}//

static PyMethodDef EDMethods[] ={

{"fact", ED_fact, METH_VARARGS, "fact( m )"}, // NOTE, the last string is doc-string of this function

{"reverse", ED_reverse, METH_VARARGS, "reverse( str )"},

{"unit_test", ED_unit_test, METH_VARARGS, "unit_test()"},

{NULL, NULL},

};//

voidinitED()

{

Py_InitModule("ED", EDMethods);

}

setup.py

#!/usr/bin/env python

from distutils.core importsetup, Extension

MOD= 'ED'setup(name=MOD, ext_modules=[

Extension(MOD, sources=['ExtDemo.c', "ExtDemo_Wrapper.c"])])

2) Visual Studio 2013 工具准备及编译

开始菜单打开 Visual Studio Tools 文件夹,

c65cba9763a3feb7ace4f20fc40f1f0a.png

选择 64bit Native Tools,双击打开,

851202bb371c1bc1480ac218c042dac0.png

设置编译环境,如下, 关于这两个参数的含义请参考 distutils.core 官方 help 文档,

set DISTUTILS_USE_SDK=1set MSSdk=1

d10959b30ae12135a5ae9a4dd5ada7d5.png

切换到工程目录,编译,

0cae3645922f684d1017064c2eff70ae.png

编译完成后,在工程目录下生成 build 文件夹,

5b06ce5aef597aac35038a14ed7b24d9.png

在其中 \build\lib.win-amd64-2.7 下得到编译生成的 pyd 文件,本例为 ED.pyd

aee7409defec76f9b521b614166bbb40.png

3) 验证

766744f6b533038c4d8aa43327a9065e.png

完。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值