Problems encountered in python calling so parameter settings using ctypes and Solutions

  • 2021-06-28 13:23:47
  • OfStack

problem

Recently, when doing a group of voiceprint clustering, we used a voiceprint distance algorithm developed by another team of students.The algorithm provides a set of so packages for external use and needs to be used by itself.Calling pure so package 1 in python generally uses the ctypes class library, which looks simple to use but has many details that can be easily mistaken.In this use process, we will encounter the problem of data transmission.

The function for the external export in the target so library is approximately three functions as follows:


void* create_handler();
  int extract_feature(void* hander);
  bool destroy(void* handler);

These three functions are easy to use, but can be used in sequence.However, when python code is found as follows, execution occurs directly to segment fault.


import sys
  import ctypes
  so = ctypes.CDLL("./lib/libbase.so")
  p = so.create_handler()
  feature = so.extract_feature(p)
  so.destroy(p)

Solve

In this code, p is of type int, which is automatically transferred by void*, and in ctyeps this transformation itself is OK.segment fault occurred in extract_In the feature function call, the problem should be in the parameters. The returned handler is no longer the original pointer, resulting in an error in the access pointer.

After consulting the ctypes documentation, it is found that ctypes can declare parameters and return types of functions in the so library.Try it, the problem is solved after the display declaration, proving that our guess is correct, and indeed the pointer has changed.Modify the code as follows:


import sys
  import ctypes
  so = ctypes.CDLL("./lib/libbase.so")
  so.create_handler.restype=ctypes.c_void_p
  so.extract_feature.argtypes=[ctypes.c_void_p]
  so.destroy.argtypes=[ctypes.c_void_p]
  p = so.create_handler()
  feature = so.extract_feature(p)
  so.destroy(p)

Conclusion:

Passing a pointer type parameter in ctypes requires that the parameters declaring the c function be displayed, with a return type.

summary


Related articles: