繁体   English   中英

使用Ctypes传递数组

[英]Passing an array using Ctypes

所以我的python程序是

from ctypes import *
import ctypes

number = [0,1,2]
testlib = cdll.LoadLibrary("./a.out")


testlib.init.argtypes = [ctypes.c_int]
testlib.init.restype = ctypes.c_double

#create an array of size 3
testlib.init(3)

#Loop to fill the array

#use AccessArray to preform an action on the array

C部分是

#include <stdio.h>


double init(int size){
    double points[size];

    return points[0];
}

double fillarray(double value, double location){

    // i need to access 
}

double AccessArray(double value, double location){

    // i need to acess the array that is filled in the previous function
}

因此,我需要做的是将数组从python部分传递到C函数,以某种方式将C中的该数组移到另一个函数中,以便对其进行处理。

我被卡住了,因为我找不到在C部分中移动数组的方法。

有人可以告诉我该怎么做吗?

您应该尝试这样的事情(在您的C代码中):

#include <stdio.h>

double points[1000];//change 1000 for the maximum size for you
int sz = 0;

double init(int size){
    //verify size <= maximum size for the array
    for(int i=0;i<size;i++) {
        points[i] = 1;//change 1 for the init value for you
    }
    sz = size;
    return points[0];
}

double fillarray(double value, double location){
    //first verify 0 < location < sz
    points[(int)location] = value;    
}

double AccessArray(double value, double location){
    //first verify 0 < location < sz
    return points[(int)location];
}

这是一个非常简单的解决方案,但是如果您需要分配任意大小的数组,则应研究malloc的使用

也许是这样的吗?

$ cat Makefile

go: a.out
        ./c-double

a.out: c.c
        gcc -fpic -shared c.c -o a.out

zareason-dstromberg:~/src/outside-questions/c-double x86_64-pc-linux-gnu 27062 - above cmd done 2013 Fri Dec 27 11:03 AM

$ cat c.c
#include <stdio.h>
#include <malloc.h>


double *init(int size) {
    double *points;

    points = malloc(size * sizeof(double));

    return points;
}

double fill_array(double *points, int size) {
    int i;
    for (i=0; i < size; i++) {
        points[i] = (double) i;
    }

}

double access_array(double *points, int size) {
    // i need to access the array that is filled in the previous function
    int i;
    for (i=0; i < size; i++) {
        printf("%d: %f\n", i, points[i]);
    }
}
zareason-dstromberg:~/src/outside-questions/c-double x86_64-pc-linux-gnu 27062 - above cmd done 2013 Fri Dec 27 11:03 AM

$ cat c-double
#!/usr/local/cpython-3.3/bin/python

import ctypes

testlib = ctypes.cdll.LoadLibrary("./a.out")

testlib.init.argtypes = [ctypes.c_int]
testlib.init.restype = ctypes.c_void_p

#create an array of size 3
size = 3
double_array = testlib.init(size)

#Loop to fill the array
testlib.fill_array(double_array, size)

#use AccessArray to preform an action on the array
testlib.access_array(double_array, size)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM