python-调用C库,python-调用c,$ cat myte


$ cat mytestlib.c#include <stdio.h> #include <stdlib.h> int subPrint(int a, int b){ printf("%d - %d = %d \n", a, b,a-b); return a-b; }gcc -g -o libpycall_c.so -shared -fPIC mytestlib.c>>> import ctypes >>> lib = ctypes.CDLL("./libpycall_c.so") >>> lib.subPrint(12, 34)12 - 34 = -22 -22
$ cat mytestlib.cpp#include <iostream>using namespace std;int subPrint_(int a, int b){    int c;    c=a-b;    cout <<a << "-" << b <<"="<< c << endl;    return c;}extern "C" {   int subPrint(int a, int b){       return subPrint_(a, b);      }}>>> import ctypes >>> import ctypes >>> lib = ctypes.CDLL("./libpycall.so")   >>> lib.subPrint(15, 3) 15-3=1212
$ cat mytestlib.cpp#include <iostream>//dmyhaspl.github.iousing namespace std;class AccumulationLib{    private:        int first=0;    int end=0 ;    public:        void setNumber(int first,int end){        this->first=first;        this->end=end;        }        long accumulate(){           long sum=0;       for(int num=first;num<=end;num++){           cout<<num<<" ";           sum+=num;       }            return sum;    }        int getFirstNumber(){            return first;        }        int getEndNumber(){        return end;    }}; extern "C" {    AccumulationLib obj;    void setNumber(int first,int end){         obj.setNumber(first,end);    }    int getFirstNumber(){        return obj.getFirstNumber();    }    int getEndNumber(){    return obj.getEndNumber();    }    long accumulate(){    return obj.accumulate();    }}>>> import ctypes>>> lib = ctypes.CDLL("./libpycall.so")>>> lib.setNumber(12,32)43364592>>> lib.accumulate()12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 462>>> print lib.accumulate()12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 462>>> lib.setNumber(12,22)43364592>>> print lib.accumulate()12 13 14 15 16 17 18 19 20 21 22 187

python-调用C库

评论关闭