python调用c编写的.so

1.编写一个简单的c .so

/* 1.1 vim sum.c */

#include <stdio.h>
#include <stdlib.h>
/*
 * gcc sum.c -fPIC -shared -o sum.so
 * 或者
 * -g -Wall 供调试使用,不是必须的
 * gcc -Wall -g  -fPIC -c sum.c -o sum.o
 * gcc -shared sum.o -o sum.so
 * 
 */

void echo(char* msg){
    printf("%s\n",msg);
}

int max(int a,int b)
{
    return a>b?a:b;
}

int sum(float a,float b){
    return a+b;
}

int sum_array(int array[], int num){
    int i =0, sum = 0; 
    for(i=0; i<num; ++i) 
        sum += array[i];
    return sum;
}

void modify_array(int array[], int num){
    int i =0, sum = 0; 
    for(i=0; i<num; ++i) 
        array[i] *= 10;
}

/* 1.2 编译.so文件 */
gcc sum.c -fPIC -shared -o sum.so

2.编写python测试脚本

/* 2.1 vim test.py */

#!/usr/bin/python
# -*- coding: utf8 -*-
import ctypes
import numpy as np

so = ctypes.CDLL('./sum.so')

# echo
so.echo("hello")

# max
ret = so.max(1, 2) 
print(ret)

# sum  (int/string以外的类型需要转换才能识别)
ret = so.sum(ctypes.c_float(1), ctypes.c_float(2))
print(ret)

# sum_array
pyarray = [1, 2, 3, 4, 5]
carray = (ctypes.c_int * len(pyarray))(*pyarray) #有点类似malloc的方式生成carray
ret = so.sum_array(carray, len(pyarray))
print(ret)
# modify_array
pyarray = [1,2,3,4,5,6,7,8]
carray = (ctypes.c_int * len(pyarray))(*pyarray)
so.modify_array(carray, len(pyarray))
print(list(carray))

/* 2.2 测试 */
python test.py
输出结果:
  hello
  2
  3
  15
  [10, 20, 30, 40, 50, 60, 70, 80]

 

yan 19.9.3

 

参考:

https://www.cnblogs.com/yahengwang/p/9687610.html

https://www.cnblogs.com/fariver/p/6573112.html

欢迎关注下方“非著名资深码农“公众号进行交流~

发表评论

邮箱地址不会被公开。