zenmbu 发表于 2015-12-3 07:10:16

python调取C/C++的dll生成方法

  本文针对Windows平台下,python调取C/C++的dll文件。
  1.如果使用C语言,代码如下,文件名为test.c。
__declspec(dllexport) int sum(int a,int b)
{
return (a + b);
}
  如果使用C++语言,代码如下,文件名为test_cpp.cpp。

#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT int sum(int a,int b)
{
return a + b;
}

在Windows平台下,__declspec(dllexport)是必须要添加的。

2.函数的声明可以放到test.h头文件中(但不是必须的):

//test.h
int sum(int,int)
  3.编译生成dll文件。
  在Visual Studio中,生成的dll文件有32bit和64bit两种,需要和python的版本对应上,否则将会报出“WindowsError: %1 不是有效的 Win32”这个错误,如下图所示。

  我的本机上python为python 2.7.9(64bit),因此需要在Visual Studio中将工程属性设置为64位的。设置步骤如下所示,相应的64位dll在x64目录下生成。

  由于有的电脑上并没有安装C++ Run Time,如只安装32bit的python,依然加载不了32位的dll,会报出如下错误,“WindowsError: ”

  参考http://stackoverflow.com/questions/10411709/windowserror-error-126-when-loading-a-dll-with-ctypes这个链接,需要将运行库改为“MT”模式。

  4.python调用,代码如下:

from ctypes import cdll
dll = cdll.LoadLibrary('G:\keyphrase extraction\Test\TestForPython.dll')
print dll.sum(1,2)
  输出结果如下:

  ctypes变量类型、C语言变量类型和Python语言变量类型之间的关系如下所示:
  参考:http://www.ibm.com/developerworks/cn/linux/l-cn-pythonandc/#icomments

  FAQ:
  1、如果只有一个dll,如何判断它是32位的还是64位的dll?
  可以使用dumpbin工具,
  在Visual Studio自带的dumpbin工具,然后输入dumpbin /HEADERS TestForPython.dll
  machine后为(x64),可以看到这个dll是64位的;如果machin后为(x86),则为32位的dll。

  参考链接:
  http://wolfprojects.altervista.org/dllforpyinc.php
  http://stackoverflow.com/questions/10411709/windowserror-error-126-when-loading-a-dll-with-ctypes
  http://stackoverflow.com/questions/15374710/windowserror-error-193-1-is-not-a-valid-win32-application-in-python#
  http://www.ibm.com/developerworks/cn/linux/l-cn-pythonandc/#icomments
  http://blog.csdn.net/jamestaosh/article/details/4237756
  http://gashero.iyunv.com/blog/519837
页: [1]
查看完整版本: python调取C/C++的dll生成方法