Python的ctypes模块可以直接调用c/c++导出的函数,将c/c++编译成动态连接库后可供python直接调用。
如下代码,将导出2个函数:
#include <iostream> #include <windows.h> using namespace std; extern "C" __declspec(dllexport) int Add(int a, int b); extern "C" __declspec(dllexport) void Echo(char str[]); BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved) { return TRUE; } __declspec(dllexport) int Add(int a, int b) { int c = a + b; return c; } __declspec(dllexport) void Echo(char str[]) { cout << str << endl; return; }
编译为dll,命令如下:
K:DropboxcodecppProject1Project1>cl -LD test.cpp 用于 x64 的 Microsoft (R) C/C++ 优化编译器 17.00.61030 版 版权所有(C) Microsoft Corporation。保留所有权利。 test.cpp C:Program Files (x86)Microsoft Visual Studio 11.0VCINCLUDExlocale(336) : wa rning C4530: 使用了 C++ 异常处理程序,但未启用展开语义。请指定 /EHsc Microsoft (R) Incremental Linker Version 11.00.61030.0 Copyright (C) Microsoft Corporation. All rights reserved. /out:test.dll /dll /implib:test.lib test.obj 正在创建库 test.lib 和对象 test.exp
在python中调用:
import os from ctypes import * test = cdll.LoadLibrary(os.getcwd() + '/test.dll') print test print test.Add(1, 2) test.Echo("hartnett_test")
调用成功后输出:
K:Dropboxcode est>python 1.py <CDLL 'K:Dropboxcode est/test.dll', handle fabe0000 at 235beb8> 3 hartnett_test