pythonpython-cfficffi

cffi embedding_init_code import custom py files


i am trying to convert my python code to dll, in the code below under ffi.embedding_init_code i can import packages which i have installed with pip or conda like cv2, numpy, pil etc but i have created python file my_tools.py this is giving error while accessing the dll. "ModuleNotfoundError: no module named 'my_tools' "

import re
import cffi
ffi = cffi.FFI()
with open('plugin.h') as f:
    include = f.read()

ffi.embedding_api(include)

ffi.set_source("my_plugin", 
        re.sub(r'^extern(?=\s)', 'CFFI_DLLEXPORT', include, flags=re.M))

ffi.embedding_init_code("""
    from my_plugin import ffi, lib
    import keras_ocr
    import my_tools # as m_tools
    import logging
    import sys
    import cv2
    import numpy as np
    from PIL import Image
    import io
    import base64

    @ffi.def_extern()
    def hello(out_result):
        out_result=ffi.string(out_result)
        print("hello python="+str(out_result))
        return 0
""")
ffi.cdef("""
    char *strdup(const char *);
""")
ffi.compile(target="plugin-1.5.*", verbose=True)

below is my plugin.h

extern int hello(char* out_result);

how can import my own created file here.


Solution

  • There is no one-size-fits-all answer, but a quick way to get started is to add this as the first line in embedding_init_code:

    import sys; sys.path.insert(0, "/path/containing/the/python/files")