SoFunction
Updated on 2024-12-10

Problems and solutions in python using ctypes to call so pass parameter settings

concern

Recently, when doing a set of voice clustering, we used a voice distance algorithm developed by another team of students. The algorithm is provided as a set of so packages, which need to be used by the users themselves. In python call pure so package generally use ctypes library, use looks simple but there are a lot of details easy to make mistakes. In the process of this use, we encountered the problem of passing parameters.

The external export functions in the target so library are three functions along the following lines.

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

These three functions are easy to use, just use them in order. However, it was found that after writing the python code in the following form, the execution will directly segment fault.

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

tackle

In this code, p is of type int, which is automatically transferred from void*, and in ctyeps this transformation itself is fine. segment fault occurs in the extract_feature function call, and the problem should be in the parameter, and the handler passed back is no longer the original pointer, which leads to an error in accessing the pointer.

After checking the documentation of ctypes, I found that ctypes can declare the parameters and return types of functions in the so library. Tried to show that after the declaration of the problem was solved, proving that our guess was right, indeed, the pointer changes. Modified code is as follows.

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

Conclusion.

Passing pointer type parameters in ctypes requires showing the parameters of the declared c function, the return type.

summarize

The above is a small introduction to the use of python ctypes call so pass parameter settings encountered problems and solutions, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!