Python调用C代码
2014-03-12 18:44
323 查看
Python的ctypes模块可以直接调用c/c++导出的函数,将c/c++编译成动态连接库后可供python直接调用。
如下代码,将导出2个函数:
编译为dll,命令如下:
在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:\Dropbox\code\cpp\Project1\Project1>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.0\VC\INCLUDE\xlocale(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:\Dropbox\code\test>python 1.py <CDLL 'K:\Dropbox\code\test/test.dll', handle fabe0000 at 235beb8> 3 hartnett_test
相关文章推荐
- python各种类型转换
- Python 之ConfigParser
- python------大脚印
- compiled python files
- 详解Python中的__init__和__new__
- python快速入门
- Python的运算符与用法
- Python JSON decode和encode
- python 出错后可以多次尝试的代码
- python Template
- 《使用Python进行自然语言处理》学习笔记三
- python 线程中join方法的使用
- Python--WindowsError
- Python一些容易忽略的知识
- Python 存储模型
- python中的队列和栈
- python内置函数
- python xml
- 【转】Python 标准库 urllib2 的使用细节
- python base64解码TypeError: Incorrect padding错误