码迷,mamicode.com
首页 > 编程语言 > 详细

python-调用C库

时间:2018-11-12 19:49:42      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:spl   names   ret   +=   .so   out   space   code   lang   

$ 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=12
12
$ cat mytestlib.cpp
#include <iostream>
//dmyhaspl.github.io
using 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库

标签:spl   names   ret   +=   .so   out   space   code   lang   

原文地址:http://blog.51cto.com/13959448/2315928

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!