I need to convert cfgmgr32 api header(cfgmgr.h) from C to a python module. So that I can call any the C header functions from other python script
Asked
Active
Viewed 3,586 times
1 Answers
4
ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
You can use ctypes. Here are examples of calling c, c++,c++ class using python:
c example:
$ 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++ example:
$ 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++ class example:
$ 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

Evidlo
- 173
- 1
- 8

myhaspldeep
- 226
- 2
- 7
-
1Hi, welcome to Stack overflow. Do not give two separate answers to the same question. You can edit your answer if you feel you need to add something. – Rishikesh Raje Oct 22 '18 at 09:10