libw15.c
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b, int c) {
return a+b+c;
}
double add2(double a, double b, double c) {
return a+b+c;
}
int mul(int a, int b, int c) {
return a*b*c;
}
ex1.py
#coding: utf-8
# 本程式透過 ctype 模組, 直接導入 dll 動態連結庫, 並使用其函式
from ctypes import cdll,c_int,c_double
lib = "libw15.dll"
dll = cdll.LoadLibrary(lib)
#add = (lambda x,y: dll.add(c_int(x), c_int(y)))
# 以上 lambda 函式定義與下列函式相同
def add(x,y,z):
return dll.add(c_int(x), c_int(y), c_int(z))
'''
ctypes 介面僅支援整數, 長整數與字串資料型別, 若使用(雙)浮點數或其他 ctype 所不支援的
資料型別, 則必須要明確告訴 ctypes 如何進行函式傳回值的轉換, 否則無法得到精確資料
'''
def add2(x,y,z):
return dll.add2(c_double(x), c_double(y), c_double(z))
# 指定 add2 函式的資料傳回型別為 c_double
dll.add2.restype = c_double
multiply = (lambda x,y,z: dll.mul(c_int(x), c_int(y), c_int(z)))
變數1 = 12
變數2 = 10
變數3 = 15
print ("變數1加上變數2加上變數3, 其值為:",add(變數1,變數2,變數3))
print ("變數1乘上變數2乘上變數3, 其值為:",multiply(變數1,變數2,變數3))
'''
15*12 = 15*2+15*10 = 150+30 = 180
15*12 = 15*2*6 = 180
'''
變數4 = 12.345
變數5 = 10.6
變數6 = 66.6
print ("變數4加上變數5加上變數6, 其值為:",add2(變數4,變數5,變數6))
123.c complier出來的dll重新命名為->sum.pyd
#include <Python.h>
int sum2(int a, int b, int c);
int sum2(int a, int b, int c){
return a+b+c;
}
static PyObject* mod_sum(PyObject *self, PyObject *args)
{
int a;
int b;
int c;
int s;
if (!PyArg_ParseTuple(args,"iii",&a,&b,&c))
return NULL;
s = sum2(a,b,c);
return Py_BuildValue("i",s);
}
static struct PyMethodDef Mod_Methods[] = {
{"sum", mod_sum, METH_VARARGS, "Description.."},
{NULL,NULL,0,NULL}
};
static struct PyModuleDef ModMethods = {
PyModuleDef_HEAD_INIT,
"SumModule",
"SumModule_doc",
-1,
Mod_Methods
};
PyMODINIT_FUNC
PyInit_sum(void)
{
(void) PyModule_Create(&ModMethods);
}
ex2.py
'''
from sum import *
print(sum(10,20))
'''
import sum
print(sum.sum(10,20,30))
w15.c
#include<stdio.h>
#define pi 3.14159
double circlearea(double r){
return r*r*pi;
}
int plus(int a,int b,int c){
return a*b-c;
}
float bmi(float heigh,float weight){
return weight/(heigh*heigh);
}
char *mystring(char str[]){
return str;
//printf("%s",str);
}
int main(void) {
printf("%e\n",circlearea(1.));
printf("%d\n",plus(1.5,6,5));
printf("%d\n",plus(1,6,5));
printf("%f\n",bmi(1.8,60));
printf("%s\n",mystring("asd"));
mystring("asd");
return 0;
}
沒有留言:
張貼留言