(三)C++结构体与python的传输

  • 1、前言
  • 2、C++代码
  • 3、python代码
  • End

该系列文章:
(一)python调用c++代码《从C++共享链接库编译到python调用指南》
(二)ndarray(Python)与Mat(C++)数据的传输
(三)C++结构体与python的传输

1、前言


(一)python调用c++代码《从C++共享链接库编译到python调用指南》
(二)ndarray(Python)与Mat(C++)数据的传输
两篇文章中,我们已经讲解了python中如何调用有复杂依赖关系的C++代码,以及ndarray和Mat类型在两个语言之间的传入(主要针对python中opencv图像和c++中opencv图像数据传输)。

本文考虑到C++结构体也是常见数据,所以特记录一篇.

2、C++代码

// 定义结构体
typedef struct NLDJ_TC_Out
{
    int test0;
    float test1;
    int test2[4];
}NLDJ_TC_Out;


extern "C"{
    // 定义一个返回结构体的函数
    NLDJ_TC_Out get_struct(){
        // 结构体
        NLDJ_TC_Out result;
        result.test0=1;
        result.test1=2.2;

        for (int i=0;i<4;i++){
            result.test2[i]=i;
        }

        return result;  // 返回结构体
    }  

}

上述代码因为不存在依赖关系,所以可以直接使用g++ -o StructCls.so -shared -fPIC StructCls.cpp编译成共享链接库

3、python代码

python代码主要完成调用函数,接收返回的结构体,主要步骤:

  1. 定义结构类(相当于映射C++中的结构)
  2. 定义返回类型的数据类型
  3. 调用
import ctypes
from ctypes import *

# 加载共享链接库
structcls = ctypes.cdll.LoadLibrary("build/StructCls.so")


# python中将结构体定义为类
class Struct_NLDJ_TC_Out(Structure):
    _fields_ = [("test0", c_int), ("test1", c_float), ("test2", c_int * 4)]

# 定义返回类型的数据类型
structcls.get_struct.restype = Struct_NLDJ_TC_Out

# result已经是转为python中定义的Struct_NLDJ_TC_Out了
# 所以result是可以按python语法输出
result = structcls.get_struct()
print(result.test2[1])

结果图:
在这里插入图片描述

End

参考:Python调用c++的动态dll中数据映射(Mat类型传递及结构体传递)

你可能感兴趣的:(Python,python,c++,opencv)