python 调用so dll动态链接库

来源:互联网 发布:数据统计分析 需要 编辑:程序博客网 时间:2024/04/30 15:47

ctypes使得python能够直接调用c语言开发的动态链接库,非常强大。
为了使用CTypes,你必须依次完成以下步骤:
* 编写动态连接库程序
* 载入动态连接库
* 将Python的对象转换为ctypes所能识别的参数
* 使用ctypes的参数调用动态连接库中的函数

一、Windows下使用Python的ctypes调用Dll动态链接库

  1. 编写dll文件

    打开VS2008,新建一个VC工程,选择Win32类型,Win32项目,用程序类型选择DLL………
    调用方式见Linux调用方式。

二、Linux下使用Python的ctypes调用so动态链接库

  1. 编写so文件
    1//test.h
    2#include   "stdio.h"
    3 
    4void test();
    5float add(float,float);
    01//test.c
    02#include "test.h"
    03 
    04void test()
    05{
    06    printf("Hello Dll...\n");
    07}
    08 
    09float add(floata,float b)
    10{
    11    returna + b;
    12}
    1gcc -fPIC -shared test.c -o libtest.so
    2 
    3#-fPIC  编译成位置无关代码,必须  不然你的程序在别的地方肯可能运行不了  
    4#-shared  当然是说要编译成共享库了
  2. Python调用so动态链接库
    01#!/usr/bin/env python
    02# -*-coding:UTF-8-*-
    03 
    04print "sss"
    05 
    06from ctypes import *
    07 
    08test =cdll.LoadLibrary("./libtest.so")
    09 
    10test.test()
    11 
    12add =test.add
    13add.argtypes =[c_float, c_float]# 参数类型,两个float(c_float内ctypes类型)
    14add.restype =c_float
    15 
    16print add(1.2,19.2)

发的

Related posts:

  1. Flash/Python Socket之前使用Python socket都从socket.socket server_ …继续阅读 »...
  2. Python WebSocket Server手机中,使用HTML5中引入的WebSocket技术来取代PC端基于flash的 …继续阅读 »...
  3. Python 手册[url]http://www.uplinux.com/download/doc …继续阅读 »...
  4. Linux中C/C++头文件说明1、 Linux中一些头文件的作用: <assert.h>:ANSI …继续阅读 »...
  5. 及时阻止SSH暴力破解入侵者方法最近,老是发现有很多暴力破解SSH密码的入侵者,虽然服务器密码设置的很复杂,但是 …继续阅读 »...

转自:http://www.xinze.me/python-%E8%B0%83%E7%94%A8so-dll%E5%8A%A8%E6%80%81%E9%93%BE%E6%8E%A5%E5%BA%93/


原创粉丝点击