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 .
// 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
python The code mainly calls the function , Receive the returned structure , Main steps :
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 :
Reference resources :Python call c++ The dynamics of the dll Data mapping in (Mat Type passing and structure passing )