程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

(3) Transfer between c++ structure and python

編輯:Python

  • 1、 Preface
  • 2、C++ Code
  • 3、python Code
  • End

The series :
( One )python call c++ Code 《 from C++ Shared link library compiled to python Call Guide 》
( Two )ndarray(Python) And Mat(C++) Data transmission
( 3、 ... and )C++ Structure and python The transmission of

1、 Preface

stay
( One )python call c++ Code 《 from C++ Shared link library compiled to python Call Guide 》
( Two )ndarray(Python) And Mat(C++) Data transmission
In two articles , We have explained python How to call a with complex dependencies C++ Code , as well as ndarray and Mat Type passing between two languages ( Mainly aimed at python in opencv Images and c++ in opencv Image data transmission ).

This paper considers C++ Structures are also common data , So I made a special record .

2、C++ Code

// Defining structure 
typedef struct NLDJ_TC_Out
{

int test0;
float test1;
int test2[4];
}NLDJ_TC_Out;
extern "C"{

// Define a function that returns a structure 
NLDJ_TC_Out get_struct(){

// Structure 
NLDJ_TC_Out result;
result.test0=1;
result.test1=2.2;
for (int i=0;i<4;i++){

result.test2[i]=i;
}
return result; // Return to the structure 
}
}

The above code has no dependencies , So you can use it directly g++ -o StructCls.so -shared -fPIC StructCls.cpp Compile into a shared link library

3、python Code

python The code mainly calls the function , Receive the returned structure , Main steps :

  1. Define structure classes ( Equivalent to mapping C++ In the structure )
  2. Define the data type of the return type
  3. call
import ctypes
from ctypes import *
# Load shared link library 
structcls = ctypes.cdll.LoadLibrary("build/StructCls.so")
# python Define a structure as a class 
class Struct_NLDJ_TC_Out(Structure):
_fields_ = [("test0", c_int), ("test1", c_float), ("test2", c_int * 4)]
# Define the data type of the return type 
structcls.get_struct.restype = Struct_NLDJ_TC_Out
# result Has been converted to python As defined in Struct_NLDJ_TC_Out 了 
# therefore result Yes, you can press python Syntax output 
result = structcls.get_struct()
print(result.test2[1])

Result chart :

End

Reference resources :Python call c++ The dynamics of the dll Data mapping in (Mat Type passing and structure passing )


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved