当前位置:编程学习 > python >>

Python调用C程序的2种方法代码讲解

方法一:直接调用动态库
from ctypes import *
libc = cdll.LoadLibrary("/lib/libc.so.6")
libc.printf("hehe%d", 199)
参考:一段python调用.so动态库的代码

---------------------------- test.py
#! /usr/bin/env python
import ctypes


lib_handle = ctypes.CDLL(./libfun.so)

test = lib_handle.test
print test(5)

testA = lib_handle.testA
print testA(1, 3)

testB = lib_handle.testB
print testB(aaaaaaaaaaaaaaaaaaaaa)
testB.restype = ctypes.c_char_p
print testB(bbbbbbbbbbbbbbbbbbbbbbb)

class AA(ctypes.Structure):
 _fields_=[("a", ctypes.c_int),("b", ctypes.c_int)]
 
aa = AA()
aa.a = 1
aa.b = 8
testC = lib_handle.testC
print testC(ctypes.byref(aa))

testD = lib_handle.testD
print testD(ctypes.byref(aa)), aa.a, aa.b

class BB(ctypes.Structure):
 _fields_=[("a", ctypes.c_int),("pB", ctypes.c_char_p),("c", ctypes.c_int)]

bb = BB()
bb.a = 1
bb.pB = ssssssssssssssssssss
bb.c = 2
testE = lib_handle.testE
testE.restype = ctypes.c_char_p
print testE(ctypes.byref(bb)), bb.a, bb.c

bb.pB = None
testF = lib_handle.testF
print testF(ctypes.byref(bb)), bb.a, bb.pB, bb.c

print lib_handle

------------------------ fun.h------------------
int test(int a);
int testA(int a, int b);
char *testB(char *p);

typedef struct _AA
{
 int a;
 int b;
}AA, *PAA;

int testC(AA *p);
int testD(AA *p);

typedef struct _BB
{
 int a;
 char *pB;
 int c;
}BB, *PBB;

char *testE(BB *p);
int testF(BB *p);
--------------------------------fun.c -------------------------------
#include "fun.h"
int test(int a)
{
 return a;
}

int testA(int a, int b)
{
 return a b;
}

char *testB(char *p)
{
 return p;
}

int testC(AA *p)
{
 return p->a p->b;
}

int testD(AA *p)
{
 int tmp = p->a;
 p->a = p->b;
 p->b = tmp;
 return 0;
}

char *testE(BB *p)
{
 int tmp = p->a;
 p->a = p->c;
 p->c = tmp;
 return p->pB;
}

int testF(BB *p)
{
 int tmp = p->a;
 p->a = p->c;
 p->c = tmp;
 p->pB = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
 return 0;
}

对参数和返回变量设置类型 (因为缺损是int类型,如果返回类型是float和double就需要进行定义)
libc.add.argtypes = [c_float,c_float]
libc.add.restype = c_float
a=libc.add(3,5)

 

方法二: 通过SWIG接口
http://www.swig.org/Doc1.3/Python.html#Python_nn7

$ swig -python example.i
*************************************
%module example

%inline %{
extern int fact(int);
extern int mod(int, int);
extern double My_variable;
%}

%include embed.i       // Include code for a static version of Python
***************************************

$ python setup.py build_ext --inplace
**************************************
#!/usr/bin/env python

"""
setup.py file for SWIG example
"""

from distutils.core import setup, Extension

example_module = Extension(_example,
                           sources=[example_wrap.c, example.c],

补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,