python调用c的方法研究了三天,今天看了一篇博客
原来这么简单,可能是最简单的方法了吧。下面整理一下思路
实验平台:
window xp系统,编译环境是vs2005
实验步骤:
步骤1:
在vs2005下编写c模块
代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include "Python.h"
_declspec(dllexport) int fac(int n)
{
printf("fac fn run.\n");
if(n < 2)
return 1;
return n * fac(n - 1);
}
步骤2:
编译生成dll库
步骤3:
在python中加载动态库并测试。
代码如下
def test_py_call_clib():
from ctypes import *
import os
test_other = cdll.LoadLibrary(os.getcwd() + '/test_other.dll')
print "load library success."
print test_other.fac(4)
if __name__ == "__main__":
test_py_call_clib()
注意加载动态库的目录
参考
http://coolshell.cn/articles/671.html
原来这么简单,可能是最简单的方法了吧。下面整理一下思路
实验平台:
window xp系统,编译环境是vs2005
实验步骤:
步骤1:
在vs2005下编写c模块
代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include "Python.h"
_declspec(dllexport) int fac(int n)
{
printf("fac fn run.\n");
if(n < 2)
return 1;
return n * fac(n - 1);
}
步骤2:
编译生成dll库
步骤3:
在python中加载动态库并测试。
代码如下
def test_py_call_clib():
from ctypes import *
import os
test_other = cdll.LoadLibrary(os.getcwd() + '/test_other.dll')
print "load library success."
print test_other.fac(4)
if __name__ == "__main__":
test_py_call_clib()
注意加载动态库的目录
参考
http://coolshell.cn/articles/671.html