Seppukki
Seppukki

Reputation: 573

python cffi breaks when used from external file

I'm writing a self organising map implementation in c and I'm trying to bind it to python using cffi.

My wrapper module looks like this:

from ._SOM import ffi, lib

lib.init()


class SOM:
    def __init__(self, x, y, input_length, sigma, learning_rate):
        self.C_som = lib.createSOM(x, y, input_length, sigma, learning_rate)

    def random_weights_init(self, data):
        newData = []
        for d in data:
            temp = ffi.new(f"double[{len(data)}]")
            for index, elem in enumerate(d):
                temp[index] = elem
            newData.append(temp)
        lib.random_weights_init(self.C_som, newData, len(data))

    def train(self, data, iterations):
        newData = []
        for d in data:
            temp = ffi.new(f"double[{len(data)}]")
            for index, elem in enumerate(d):
                temp[index] = elem
            newData.append(temp)
        lib.train(self.C_som, newData, len(data), iterations)

    def winner(self, data):
        res = lib.winner(self.C_som, data)
        x = res[0]
        y = res[1]
        lib.free(res)
        return x, y


if __name__ == "__main__":
    S = SOM(10, 10, 3, 0.67, .05)
    S.random_weights_init([[.5, 6, 9], [7, 8, 7], [7, 7, 7]])
    S.train([[.5, 6, 9], [7, 8, 7], [7, 7, 7]], 10)
    r = S.winner([7, 8, 7])
    print(r)

When running this file I works fine when I change line 1 to

from _SOM import ffi, lib

When importing my wrapper class in another file like this:

from .SOM.SOM_test import SOM as C_SOM

and try to use it, I get the following error:

Process finished with exit code -1073740940 (0xC0000374)

When looking the code up, I found it means heap corruption. Is there a fault in my C source code? Or is something wrong with my imports?

EDIT

There was an issue with the C code itself. There was a struct field of type double*** and I was mallocing float**, float* and float into it.

Upvotes: 0

Views: 68

Answers (1)

Seppukki
Seppukki

Reputation: 573

There was an issue with the C code itself.
There was a struct field of type double*** and I was mallocing float**, float* and float into it. This would most likely be the cause of the heap corruption.

Upvotes: 0

Related Questions