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

myTest.cpp:

#include<iostream>
#include<vector>

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

private:

};

MyTest::MyTest()
{
}

MyTest::~MyTest()
{
}

int MyTest::myTest(int* myData,int dataNum)
{
    if (dataNum>0)
    {
        for (size_t i = 0; i < dataNum; i++)
        {
            *myData = i + 2;
            myData += 1;
        }
    }

    return 0;
}


extern "C" {

    MyTest myObj;

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

}

 编译生成:g++ testpy.cpp  -fPIC -shared -o libtest.so -std=c++11

 

 

pythonCallCpp.py:

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

from ctypes import *
import ctypes

INPUT = c_int * 100
input = INPUT()

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

lib.myTest(input, 100)  

print input[0]
print input[1]
print input[2]
print input[3]

 python pythonCallCpp.py     结果:

2
3
4
5

posted @ 2019-07-29 15:19  玥茹苟  阅读(665)  评论(0编辑  收藏  举报