python调用c++类方法(2)

testpy.cpp:

#include<iostream>
#include<vector>

struct point{
  float pointx;
  float pointy;
  float pointz; 
};

struct pose{
  float x;
  float y;
  float z;
  int* data;
  
  point location;
};


class MyTest
{
public:
    MyTest();
    ~MyTest();
    int myTest(int* myData, int dataNum, pose& mypose);

private:

};

MyTest::MyTest()
{
}

MyTest::~MyTest()
{
}

int MyTest::myTest(int* myData, int dataNum, pose& mypose)
{
    if (dataNum>0)
    {
        for (size_t i = 0; i < dataNum; i++)
        {
            *myData = i + 2;
            myData += 1;
        }
    }
 mypose.x=1.0;
 mypose.y=2.0;
 mypose.z=3.0;
 mypose.location.pointx=4.0;
 mypose.location.pointy=5.0;
 mypose.location.pointz=6.0;
 
     if (dataNum>0)
    {
        for (size_t i = 0; i < dataNum; i++)
        {
            *(mypose.data) = i + 2;
            mypose.data += 1;
        }
    }
 
 
    return 0;
}


extern "C" {

    MyTest myObj;

    int myTest(int* myData, int dataNum, pose& mypose)
    {
        return myObj.myTest(myData, dataNum, mypose);
    }

}

pythonCallCpp.py:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from ctypes import *
import ctypes
import numpy

INPUT = c_int * 100
myinput = INPUT()

INPUT01 = c_int * 100
myinput01 = INPUT01()


#arr = numpy.array([1, 2, 3, 4],dtype = numpy.int)
arr1 = numpy.zeros(100, dtype=ctypes.c_int)

#if not arr.flags['C_CONTIGUOUS']:              # 若不是C连续内存,强制转换    
  #arr = numpy.ascontiguous(arr, dtype = numpy.dtype)
if not arr1.flags['C_CONTIGUOUS']:    
  arr1 = numpy.ascontiguous(arr1, dtype = numpy.dtype)
#c_arr = numpy.ctypeslib.as_ctypes(arr)         # array 转为ctypes类型
#c_arr1 = numpy.ctypeslib.as_ctypes(arr1)

cptr = arr1.ctypes.data_as(POINTER(ctypes.c_int))    # 取指针


so = ctypes.cdll.LoadLibrary   
lib = so("/opt/fp100/libtest.so")   
print 'myTest(int* myData, int dataNum, pose& mypos)'  

class point(ctypes.Structure):      
  _fields_ = [("pointx", ctypes.c_float),("pointy", ctypes.c_float),("pointz", ctypes.c_float)]
  
pointtemp = point(0.0, 0.0, 0.0) 

class pose(ctypes.Structure):      
  _fields_ = [("x", ctypes.c_float),("y", ctypes.c_float),("z", ctypes.c_float),("data", POINTER(ctypes.c_int)),("location", point)]      #POINTER(ctypes.c_int)
  
posetemp = pose()
posetemp.x=0.0
posetemp.y=0.0
posetemp.z=0.0

posetemp.data = myinput01
posetemp.location = pointtemp 

#posetemp = pose()

lib.myTest(myinput, 100, ctypes.byref(posetemp))  

print myinput[0]
print myinput[1]
print myinput[2]
print myinput[3]
print posetemp.x
print posetemp.y
print posetemp.z
print posetemp.location.pointx
print posetemp.location.pointy
print posetemp.location.pointz

print posetemp.data[0]

结论:存在一个问题,结构体内套指针时,出现地址紊乱,不知如何解决?

原文地址:https://www.cnblogs.com/lovebay/p/11268886.html