(转)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。在Windows平台下,__declspec(dllexport)是必须要添加的。

#define DLLEXPORT extern "C" __declspec(dllexport)

DLLEXPORT int sum(int a,int b)
{
    return a + b;
}

2.编译生成dll文件。

在Visual Studio中,生成的dll文件有32bit和64bit两种,需要和python的版本对应上,否则将会报出“WindowsError: [Error 193] %1 不是有效的 Win32”这个错误,如下图所示。

{R5%AQ8OK`[~W]6RGAGL5RA

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

W3)V@XM3Y$DGFN`FN1$Z)S7

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

HE8O4BZO]OCF`HHRN5{TOSA

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

%WRC6]DL4}R37TP2T69ITVA

3.python调用,代码如下:

from ctypes import cdll

dll = cdll.LoadLibrary('G:keyphrase extractionTestTestForPython.dll')
print dll.sum(1,2)

输出结果如下:

image

ctypes变量类型、C语言变量类型和Python语言变量类型之间的关系如下所示:

参考:http://www.ibm.com/developerworks/cn/linux/l-cn-pythonandc/#icomments

V@`%PQLFAT)~{TX$55CHJ%C

FAQ:

1、如果只有一个dll,如何判断它是32位的还是64位的dll?

可以使用dumpbin工具,

在Visual Studio自带的dumpbin工具,然后输入dumpbin /HEADERS TestForPython.dll

machine后为(x64),可以看到这个dll是64位的;如果machin后为(x86),则为32位的dll。

AV%5`SFOU@ES)Z6W9A79%_R

参考链接:

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.iteye.com/blog/519837

原文地址:https://www.cnblogs.com/heluan/p/9815971.html