python与c

1、ctypes 变量类型

from ctypes import *     
import ctypes
i = c_int(45)
print i.value

2、定义一个可变字符串变量,长度为 10

from ctypes import *     

p = create_string_buffer(10) 
p.value = 'student'
print p.raw
# 只有前三个字符被修改
p.value = '123'
print p.raw

3、C 语言指针

from ctypes import *     

c = c_int(234)
# 定义指针指向c
p = pointer(c)
print p.contents.value

c.value = 45
print p.contents.value

p.contents.value = 100
print c.value  

4、使用 C 语言数组和结构体

from ctypes import *     

# 定义一个结构,内含两个成员变量 x,y,均为 int 型
class POINT(Structure):                 
    _fields_ = [("x", c_int), 
                ("y", c_int)] 
point = POINT(2,5) 
print point.x, point.y

# 重新定义一个POINT,x取默认值
point = POINT(y=5)
print point.x, point.y

# 定义 POINT_ARRAY 为 POINT 的数组类型
POINT_ARRAY = POINT * 3            
pa = POINT_ARRAY(POINT(7, 7), POINT(8, 8), POINT(9, 9))
for p in pa: 
    print p.x, p.y

5、mac平台掉用c库函数

1)编写C代码
#include <stdio.h>
int add(int x, int y)
{
  return (x+y);  
}
char *reverse(char *s) {
    register char t;
    char *p = s;
    char *q = (s + (strlen(s) - 1));
    while (p < q) {
        t = *p;
        *p++ = *q;
        *q-- = t;
    }
    return s;
}
typedef struct{
  int a;
  int b;
}mystruct;

mystruct * create(){
  mystruct * s = (mystruct *)calloc(1, sizeof(mystruct));
  s->a = 100;
  s->b = 200;
  return s;
}

void destroy(mystruct * s){
  free(s);
}
2) 编译动态链接库
 gcc add.c -fPIC -shared -o libAdd.so
or
gcc -fPIC -shared -o libAdd.so  add.c
3)phthon导入动态链接库,调用C函数,涉及到参数类型以及函数返回类型
from ctypes import cdll 

def callc(): 
    # load the some.dll 
    so = cdll.LoadLibrary('/Users/xxxx/Desktop/python/libAdd.so') 
    # add函数很简单
    print so. add(2,3) 
if __name__== '__main__': 
    callc()

对于参数返回类型,返回地址不一致,从c代码应该是一样的

from ctypes import *
so = cdll.LoadLibrary('E:/nuli/scikit-learn/Scikit-learn/tqlq/dlltest.dll')
p = create_string_buffer(8) 
p.value = 'student'

so.reverse.restype = c_char_p

lr = so.reverse(p)
print '%x'%id(lr), '%x'%id(p.value),p,lr,p.value
2606378 3c9daa8 <ctypes.c_char_Array_8 object at 0x0000000003D10248> tneduts tneduts

调整参数类型,返回类型设为类指针,得到一致性

from ctypes import *
so = cdll.LoadLibrary('E:/nuli/scikit-learn/Scikit-learn/tqlq/dlltest.dll')

p = create_string_buffer(8) 
p.value = 'student'

so.reverse.restype = POINTER(type(p))
lr = so.reverse(p)

print '%x'%id(lr.contents.value), '%x'%id(p.value),lr.contents.value,p.value
3ac2080 3ac2080 tneduts tneduts

对于结构体类型处理

from ctypes import *
so = cdll.LoadLibrary('E:/nuli/scikit-learn/Scikit-learn/tqlq/dlltest.dll')
class mystruct(Structure):  
    _fields_ = [('a', c_int),  
                ('b', c_int)]  

so.create.restype = POINTER(mystruct)

p = so.create()
print p.contents.a, p.contents.b

so.destroy(p)
print p.contents.a, p.contents.b
100 200
释放内存后
64078736 0

6 PyObject,vs编译为xxx.dll,将xxx.dll改为xxx.pyd,然后import xxx即可

int add(int a,int b)
{
        return a+b;
}

int sub(int a,int b)
{
        return a -b;
}

int mul(int a,int b)
{
        return a*b;
}

int div1(int a,int b)
{
        if(0 == b)
        {
                return b;
        }
        return a/b;
}

PyObject* wrap_add(PyObject* self, PyObject* args) 
{
  int n1,n2, result;
  
  if (! PyArg_ParseTuple(args, "i|i", &n1,&n2))
    return NULL;
  result = add(n1,n2);
  return Py_BuildValue("i", result);
}

PyObject* wrap_sub(PyObject* self, PyObject* args) 
{
  int n1,n2, result;
  
  if (! PyArg_ParseTuple(args, "i|i", &n1,&n2))
    return NULL;
  result = sub(n1,n2);
  return Py_BuildValue("i", result);
}

PyObject* wrap_mul(PyObject* self, PyObject* args) 
{
  int n1,n2, result;
  
  if (! PyArg_ParseTuple(args, "i|i", &n1,&n2))
    return NULL;
  result = mul(n1,n2);
  return Py_BuildValue("i", result);
}
PyObject* wrap_div1(PyObject* self, PyObject* args) 
{
  int n1,n2, result;
  if (! PyArg_ParseTuple(args, "i|i", &n1,&n2))
    return NULL;
  result = div1(n1,n2);
  return Py_BuildValue("i", result);
}


static PyMethodDef exampleMethods[] = 
{
  {"add", wrap_add, METH_VARARGS, "Caculate 1!"},
  {"sub", wrap_sub, METH_VARARGS, "Caculate 2!"},
  {"mul", wrap_mul, METH_VARARGS, "Caculate 3!"},
  {"div1", wrap_div1, METH_VARARGS, "Caculate 4!"},
  {NULL, NULL,0,NULL}
};

void initexample() 
{
  PyObject* m;
  m = Py_InitModule("example", exampleMethods);
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏landv

c语言_头文件_stdlib

27830
来自专栏小樱的经验随笔

BZOJ 3097: Hash Killer I【构造题,思维题】

3097: Hash Killer I Time Limit: 5 Sec  Memory Limit: 128 MBSec  Special Judge Su...

22460
来自专栏noteless

[四] java8 函数式编程 收集器浅析 收集器Collector常用方法 运行原理 内部实现

收集器是由四个函数约定构成,它们一起工作,将条目汇集到一个可变的结果容器中,并可选择性地对结果执行最终转换。

31420
来自专栏函数式编程语言及工具

SDP(9):MongoDB-Scala - data access and modeling

    MongoDB是一种文件型数据库,对数据格式没有硬性要求,所以可以实现灵活多变的数据存储和读取。MongoDB又是一种分布式数据库,与传统关系数据库不同...

40540
来自专栏高性能服务器开发

(三)dict哈希结构3

/* This function performs just a step of rehashing, and only if there are * no...

29080
来自专栏算法修养

CodeForces 668B Little Artem and Dance

B. Little Artem and Dance time limit per test 2 second memory limit per test...

34950
来自专栏码匠的流水账

聊聊spring cloud gateway的GatewayFilter

本文主要研究一下spring cloud gateway的GatewayFilter

62810
来自专栏算法修养

PAT 1012 The Best Rank

1012. The Best Rank (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B ...

32540
来自专栏码匠的流水账

聊聊storm TridentTopology的构建

storm-core-1.2.2-sources.jar!/org/apache/storm/trident/TridentTopology.java

12520
来自专栏图形学与OpenGL

WebGL三角形旋转变换

31910

扫码关注云+社区

领取腾讯云代金券