jiaming@ubuntu:~/project $ tree . . ├── hello.c ├── hello.py └── mylib.so 0 directories, 3 files jiaming@ubuntu:~/project $ cat hello.c #include stdio.h # 字符指针 void display(char* string) { printf( "%s\n" , string);
.
├── hello.c
├── hello.py
└── mylib.so
0 directories, 3 files
jiaming@ubuntu:~/project$ cat hello.c
#include <stdio.h>
# 字符指针
void display(char* string)
{
printf("%s\n", string);
}
# 浮点传参,以及返回浮点数
float multi(float a, float b)
{
return a*b;
}
# 传入整型指针
void modify_array(int array[], int num)
{
int i = 0, sum = 0;
for(i=0; i<num; i++)
array[i] *= 10;
}
jiaming@ubuntu:~/project$ cat hello.py
import ctypes
import numpy as np
from ctypes import cdll
so = cdll.LoadLibrary('./mylib.so')
so.display("dslab")
# 规定函数参数类型以及函数返回值类型
so.multi.argtypes = [ctypes.c_float, ctypes.c_float]
so.multi.restype = ctypes.c_float
a = 2.5
b = 3.0
print so.multi(a, b)
# 将列表转换为数组传入并返回修改后的列表
pyarray = [1,2,3,4,5,6,7,8]
carray = (ctypes.c_int*len(pyarray))(*pyarray)
so.modify_array(carray, len(pyarray))
print np.array(carray)