在Python模块中调用C头文件功能

时间:2018-10-22 06:59:28

标签: python c ctypes python-module c-api

我需要将cfgmgr32 api标头(cfgmgr.h)从C转换为python模块。这样我就可以从其他python脚本调用任何C头函数

1 个答案:

答案 0 :(得分:2)

ctypes是Python的外部函数库。它提供C兼容的数据类型,并允许在DLL或共享库中调用函数。它可以用于将这些库包装在纯Python中。

您可以使用ctypes。以下是使用python调用c,c ++,c ++类的示例:
c示例:

$ cat mytestlib.c
#include <stdio.h> 
#include <stdlib.h> 
//dmyhaspl.github.io
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

c ++示例:

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

    $g++ -g -o libpycall.so -shared -fPIC -std=c++11 mytestlib.cpp

c ++类示例:

$ 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();
    }
}


   $g++ -g -o libpycall.so -shared -fPIC -std=c++11 mytestlib.cpp
   >>> 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