Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to reference use ctypes

Tags:

c++

python

My cpp program:test.cpp

#include <iostream>

using namespace std;

extern "C"
{
    void test_2(int &e, int *&f)
    {
        e=10;
        f=new int[e];
        for(int i=0;i<e;i++)
            f[i]=i;
    }
}

And this is my compile command:g++ -fPIC -shared test.cpp -o test.so my operating system is ubuntu 12.04 lts,my python version is 2.7.5,the python program like these:

#coding=utf-8

import ctypes
from ctypes import *

if __name__ == "__main__":
    lib = ctypes.CDLL("./test.so")
    a = c_int()
    b = c_int()
    lib.test_2(
        byref(a),
        byref(pointer(b))
    )
    print a.value
    print type(b)

and the output is 10 and <class 'ctypes.c_int'>,but I wanna get the number 10 and an int array,what should I do?

like image 683
Karl Doenitz Avatar asked Jun 21 '26 21:06

Karl Doenitz


1 Answers

Define b as a pointer in the first place.

#coding=utf-8

import ctypes
from ctypes import *

if __name__ == "__main__":
    lib = ctypes.CDLL("./test.so")
    a = c_int()
    b = pointer(c_int())
    lib.test_2(
        byref(a),
        byref(b)
    )
    for index in range(0,a.value):
      print b[index]
like image 180
Jean-Bernard Jansen Avatar answered Jun 23 '26 10:06

Jean-Bernard Jansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!