Question

I'm trying to use ctypes to use fann (a neural network library written in C) in python3. Here is my abridged code so far:

from ctypes import *
cdll.LoadLibrary("/usr/local/lib/libdoublefann.dylib")
fann = CDLL("/usr/local/lib/libdoublefann.dylib")


# Call fann to create a neural network
nn = fann.fann_create_from_file(b'/Users/xxxxx/Code/fanncode/net/nnf_25_1339802027.net')

# this outputs 3909360
print(nn)

If I try and call any other functions in the fann library against the nn variable, which should now be a fann neural network, I either get Segmentation fault: 11 or AttributeError: 'int' object has no attribute 'getMSE' (for example). I think my problem is that according to the ctypes documentation, the variable nn is ending up being an int, whereas the fann documentation for the function fann_create_from_file states:

FANN_EXTERNAL struct fann *FANN_API fann_create_from_file(const char * configuration_file)

So I think I need to declare:

class FANN_API(Structure):
    <fields and things which I don't know what they should be>

And then do:

fann.fann_create_from_file.restype = FANN_API

My problem is that I can't find what the struct FANN_API should be. Line 130 of fann.h states #define FANN_API but thats it, no definition or anything follows it.

Am I correct in my guess about needing to define the struct? If so, then how can I find out the format of it to declare in the python code? If not then can anybody suggest what I might need to do/what to read to get my code to work?

Thanks!

Was it helpful?

Solution

You can tell ctypes the arguments and return codes of functions. You should be able to get away with c_void_p (void*) as the type unless you have some reason to manipulate the contents of the structure:

fann.fann_create_from_file.restype = c_void_p
fann.fann_create_from_file.argtypes = [c_char_p]

Note that struct fann * is the return type of your function. FANN_API represents the calling convention. You've said it is defined as #define FANN_API. Being defined as nothing means the default calling convention, so your use of CDLL should be correct.

If you need to define something more specific, post the definition of struct fann.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top