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]

 

結論:存在一個問題,結構體內套指針時,出現地址紊亂,不知如何解決?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM