指向引用使用ctypes的指针

2024-09-17 19:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我的cpp程序: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;
    }
}

这是我的编译命令:g++ -fPIC -shared test.cpp -o test.so 我的操作系统是ubuntu 12.04 lts,我的python版本是2.7.5,python程序如下:

#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)

输出是10<class 'ctypes.c_int'>,但是我想得到数字10和一个int数组,我该怎么办?你知道吗


Tags: testimport程序soincludelibctypesnamespace
1条回答
网友
1楼 · 发布于 2024-09-17 19:47:24

首先将b定义为指针。你知道吗

#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]

相关问题 更多 >