BlenderPythonRecipes icon indicating copy to clipboard operation
BlenderPythonRecipes copied to clipboard

executing C code from python (passing and receiving arrays)

Open zeffii opened this issue 8 years ago • 0 comments

this works.. but i sense that it is not wise.

#include <stdio.h>
#include <stdlib.h>

void hello_world() {
    printf("Hello World!");
}


int* multiplyArray(int, int*);

int* multiplyArray(int aSize, int* arr){
    int i;
    int * newarr;
    newarr = calloc(aSize, sizeof(arr));

    for (i=0; i < aSize; i++){
        newarr[i] = 2 * arr[i];
    }
    return newarr;
}


int main() {
    return 0;
}

and

import ctypes

path = "C:\\Users\\zeffi\\compiles\\hello.so"

lib = ctypes.cdll.LoadLibrary(path)
lib.hello_world()
marray = lib.multiplyArray
marray.argtypes = ()
marray.restype = ctypes.POINTER(ctypes.c_int)
g = [34,35,36,37,38,22,33]
array_type = ctypes.c_int * len(g)
result = marray(ctypes.c_int(len(g)), array_type(*g))

print(result)
for i in range(len(g)):
    print(result[i])
"""
gcc -c hello_world.c      
>>> makes: hello_world.o

gcc -shared hello_world.o -o hello.so
>>> makes: hello.so

"""

zeffii avatar May 26 '17 15:05 zeffii