Python calls C/C++ library, easy to understand and contains examples

Sometimes it is necessary to use python to call the existing C/C++ library. This article will introduce how to use python's ctypes package to call C/C++, and use simple examples to verify it.

First explain how python calls a C program.
For example, in the following C program, some of the input and output parameters seem unreasonable, but here is to explain how to use python to connect the input and output parameters of the C program.

// func.c 代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

double* func(double *f, char* str)
{
    
    
   printf("%s\n",str);
   *f=2.4;
   printf("data: %f\n",*f);
   return f;
}

double * const funcArray(double x[], int n)
{
    
    
   for(int i=0;i<n;++i) x[i] = i;
   return x;
}

struct Mystruct
{
    
    
   /* data */
   double * p;
   int ndata;
};
void print(struct Mystruct x){
    
    
   printf("In func print \n");
   for(int i=0;i<x.ndata;++i) printf("%f ",x.p[i]);
   printf("\n");
}

compile it as a dynamic library

gcc func.c -shared -fPIC -o libfunc.so

Next, start writing python code, first load libfunc.sothe C library:

from ctypes import *
dll = cdll.LoadLibrary
lib = dll('./libfunc.so')

Next, the data interaction of three types of data between python and C language is shown, including 基本数据类型, 数组, 结构体.

1. Data interaction of basic data types, double* func(double*, char*)described by functions

# C程序func函数的返回参数为(double *),所以首先在python中说明返回类型
lib.func.restype = POINTER(c_double) # 返回double *
# int,double,char在python中可以直接用 c_int,c_double等直接定义,但指针类型对象需要用
# byref来获取指针,指针类型的定义需要用POINTER(type)来定义,最后,字符串会特殊一些,需要用到
# create_string_buffer才可以在C程序中进行修改字符串
buf = create_string_buffer('hello world'.encode('gbk')) # 要输入的字符串
data = c_double(1.2) # double类型数据
# 调用函数
res = lib.func(byref(data), buf) #调用函数,参数为 (double*, char *)
# 输出结果
print(buf.value)
print(res[0])

2. The data interaction of the array is double*const funcArray(double x[],int n)explained by the function

# 首先说明返回类型
lib.funcArray.restype = POINTER(c_double) # 返回为double *
# 关键:定义一个数组
array = c_double *10 # 定义数组
x = array() # 数组空初始化

lib.funcArray(x,10)  # 调用函数,参数为(double x[], int)

for i in range(10):
   print(x[i])

3. The data interaction of the structure is print(Mystruct s)explained by the function

ndata = 10
# 定义数组类型,用于初始化结构体中的成员变量
array = c_double*ndata

class Mystruct(Structure):
   _fields_=[
      ('p',POINTER(c_double)),
      ('ndata',c_int)
   ]

s = Mystruct()
s.ndata = ndata
s.p = array()
for i in range(s.ndata):
   s.p[i] = i
# 调用C程序函数
lib.print(s)

To call a C++ program from python, you need to first write the interface of C calling C++ (you can refer to my blog: Jump to blog ), and then call it according to the method in this article.

Guess you like

Origin blog.csdn.net/Meiyuan2021/article/details/129933966