---
title: "gcc编译dll,python加载"
author: "westice"
date: "2011-04-07T10:51:29Z"
tags: []
categories: ["编程语言"]
slug: "gcc-dll-python"
draft: false
lastmod: "2011-04-07T10:52:45Z"
id: 989043
url: "https://westice.iteye.com/blog/989043"
---

python开发效率高，实际项目时python搭建整个项目框架，关键模块用c编写，是个不错的办法！

   c函数对python的接口要按规则写。

   比如一个阶乘c函数的头文件定义：

   dll.h:

```
#ifndef LIB_H  
#define LIB_H  
extern "C" long __declspec(dllexport)factorial(int n);  //接口定义
#endif  
```

 

   dllmain.c:

 

```
#include "dll.h"  

long factorial(int n){
    if(n == 1)return 1;
    return n * factorial(n - 1);
}
```

   然后用gcc编译成dll文件。

         gcc -Wall -shared dllmain.c -o dllmain.dll

  或者 gcc --shared dllmain.c -o dllmain.dll

  刚开始gcc提示找不到cc1.exe,在dev-cpp mingw32中有个cc1plus.exe的文件，改成cc1.exe拷贝到gcc bin目录中即可。

  生成的dll就可以使用了。

```
from ctypes import *

#libtest=CDLL("dllmain.dll")
libtest=cdll.LoadLibrary("dllmain.dll")
print libtest.factorial(10)
```