这里编写个简单例子来说明下具体是如何操作的:
建立DLL项目,结构如下:
test/
----mydll.h
----mydll.c
头文件:mydll.h
#ifndef __MYDLL_H__
#define __MYDLL_H__
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
DLL_EXPORT int __stdcall foo(int x);
#ifdef __cplusplus
}
#endif
#endif // __MYDLL_H__
C文件:mydll.c
#include "mydll.h"
DLL_EXPORT int __stdcall foo(int x) {
return x;
}
如果你安装了Code::Blocks(和MinGW),那么创建环境变量:
MINGW_HOME="C:\Program Files\CodeBlocks\MinGW"
PATH=%MINGW_HOME%\bin;%PATH%
打开命令行,进入我们的项目路径中:
d:\test>
#执行编译命令
d:\test>mingw32-gcc -c -DBUILD_DLL mydll.c
#执行链接命令,生成mydll.dll和静态库文件libmydll.a
d:\test>mingw32-gcc -shared -o mydll.dll mydll.o -Wl,--kill-at,--out-implib,libmydll.a
以上,就是我们生成DLL的全过程了。
用Python测试下:
>>> import ctypes
>>> mydll = ctypes.windll.LoadLibrary("d:\\test\\mydll.dll")
>>> print mydll.foo(10)
10
MinGW在Vista中运行时cannot exec `cc1'问题:
假设环境变量PATH已经设置了MinGW路径为C:/MinGW/bin;
但是在Make时无法正确执行,出现:
g++: installation problem, cannot exec `cc1plus': No such file or directory
解决方法:
将C:/MinGW//libexec/gcc/mingw32/3.4.5/的 cc1和cc1plus两个文件
复制至C:/MinGW/bin
MinGW在Vista中运行时cannot exec `cc1’问题:
假设环境变量PATH已经设置了MinGW路径为C:/MinGW/bin;
但是在Make时无法正确执行,出现:
g++: installation problem, cannot exec `cc1plus’: No such file or directory
解决方法:
将C:/MinGW//libexec/gcc/mingw32/3.4.5/的 cc1和cc1plus两个文件
复制至C:/MinGW/bin
password.c
#include "password.h"
DLL_EXPORT char* __stdcall foo(char *x)
{
int sizex=sizeof(x)/sizeof(x[0]);
char temp[sizex];
int i;
char *te = &temp;
for(i=0;i<sizex;i++)
{
if(*(x+i)=="\n")
{break}
temp[i]=*(x+i);
}
temp[sizex]="\0";
return temp;
//return x;
}
password.h
#ifndef __PASSWORD_H__
#define __PASSWORD_H__
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
DLL_EXPORT char* __stdcall foo(char *x);
#ifdef __cplusplus
}
#endif
#endif // __PASSWORD_H__
test.py
import os
import ctypes
from ctypes import c_char_p
def tests():
os.chdir(r'C:\Documents and Settings\Administrator\桌
面\2018-08-02')
pa=ctypes.windll.LoadLibrary('password.dll')
print(pa.foo(c_char_p(b'abc')))
return pa
pa=tests()
print(pa.foo(c_char_p(b'abcd')))
rst=ctypes.string_at(pa.foo(c_char_p(b'abcd')),-1)
print(rst.decode('utf-8'))