【问题标题】:Call C header file functions in a Python module [closed]在 Python 模块中调用 C 头文件函数 [关闭]
【发布时间】:2019-03-26 04:51:40
【问题描述】:

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

【问题讨论】:

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


【解决方案1】:

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

您可以使用 ctypes。下面是使用python调用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

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


$ python 
>>> 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

$ python
>>> 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

【讨论】:

  • 嗨,欢迎来到 Stack Overflow。不要对同一个问题给出两个不同的答案。如果您觉得需要添加一些内容,可以编辑您的答案。
猜你喜欢
  • 2020-12-14
  • 1970-01-01
  • 2012-11-26
  • 2012-12-07
  • 1970-01-01
  • 2020-09-03
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多