zeffii / BlenderPythonRecipes

curated snippets for bpy (mostly for Blender <= 2.79 ), some changes are needed to maintain compatibility with 2.8+
GNU General Public License v2.0
121 stars 9 forks source link

executing C code from python (passing and receiving arrays) #5

Open zeffii opened 7 years ago

zeffii commented 7 years ago

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

"""