'How to insert a C struct dynamic link lib into Python using ctypes?

  • I wrote a python code embedded with C code by using ctypes.

  • the C code is as follows:

  • test.h

#include<Python.h>

PyObject *getFeature(wchar_t *text);
// where the unigram is a Set Object with type 'PySetObject'
  • test.c
#include<test.h>

PyObject *getFeature(wchar_t *text)
{
    int ret = -1;
    // the below three line is to initialize for the following statements.
    // they are not being used because this func is a simple version.
    const wchar_t *startFeature = L"[START]";
    const wchar_t *endFeature = L"[END]";
    const wchar_t *delim = L".";

    PyObject *featureList = PyList_New(0);

    PyObject *curString = PyUnicode_FromWideChar(text, 2);
    ret = PyList_Append(featureList, curString);
    Py_DECREF(curString);
    return featureList;
}
  • the above C code is a simple version, and the whole C code is at thw whole C code and there exists about 20 const wchar_t * variables initialized in the beginning of the C function

  • and then I compiled it and get a shared lib called libtest.so. So I can import this C .so file into the python code with ctypes like below:

  • test.py

import ctypes

dir_path = 'path/to/the/libtest.so'
feature_extractor = ctypes.PyDLL(
    os.path.join(dir_path, 'libtest.so'))
get_feature_c = feature_extractor.getFeature
get_feature_c.argtypes = [
    ctypes.c_wchar_p, ctypes.py_object]
get_feature_c.restype = ctypes.py_object

def get_feature(text):
    return [text[:2]]

times = 100000
for i in range(times):
    res = get_feature_c('ncd')  # this func will always initialized const wchar_t * variables first
  • and in this example, those three initialization statements const wchar_t *startFeature and etc. is being initialized every time in the loop when calling the C func.

  • the question is :

    • I wanna first initialize those const wchar_t* variables in the python code and then call the get_feature_c func, just like a c++ class, thus avoiding executing the initialization in every loop.
    • So, how to use ctypes to realize my needs? and I only find that ctypes wraps a C func, and can not wrap a C struct to form a class like c++.
  • Thank you very much, outperforming programming master~



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source